Android保存App異常信息到本地
本文實(shí)例為大家分享了Android保存App異常信息到本地的具體代碼,供大家參考,具體內(nèi)容如下
首先添加權(quán)限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
代碼
// 調(diào)用該方法造成異常
private void math() {
try {
int a = 0;
int b = 10;
int c = b / a;
} catch (Exception e) {
e.printStackTrace(); // Logcat打印異常
// 保存異常信息
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
saveException(this, sw.toString());
}
}
/**
* 保存異常信息到本地 Android/data/包名/files/Documents/exception/yyyyMMdd_app_exception.txt
* @param context 上下文
* @param errMsg 異常信息
*/
private void saveException(Context context, String errMsg) {
if (context == null || TextUtils.isEmpty(errMsg)) return;
FileOutputStream fos = null;
try {
// 創(chuàng)建目錄
String dirPath = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS).getPath() + "/exception/";
File dir = new File(dirPath);
if (!dir.exists()) {
dir.mkdirs();
}
// 根據(jù)當(dāng)天日期來(lái)生成文件名
String date = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH).format(new Date());
// 創(chuàng)建文件
File file = new File(dirPath, date + "_app_exception.txt");
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file, true);
fos.write(errMsg.getBytes());
fos.write("\n".getBytes());
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
效果如圖


可以考慮將當(dāng)前時(shí)間寫進(jìn)文件,更方便排查問(wèn)題
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Android基于OpenCV實(shí)現(xiàn)霍夫直線檢測(cè)
霍夫變換利用點(diǎn)與線之間的對(duì)偶性,將圖像空間中直線上離散的像素點(diǎn)通過(guò)參數(shù)方程映射為霍夫空間中的曲線,并將霍夫空間中多條曲線的交點(diǎn)作為直線方程的參數(shù)映射為圖像空間中的直線。給定直線的參數(shù)方程,可以利用霍夫變換來(lái)檢測(cè)圖像中的直線。本文簡(jiǎn)單講解Android的實(shí)現(xiàn)2021-06-06
Android實(shí)現(xiàn)界面的自動(dòng)跳轉(zhuǎn)功能
界面自動(dòng)跳轉(zhuǎn)是指在應(yīng)用啟動(dòng)或某個(gè)特定界面顯示后,經(jīng)過(guò)預(yù)定的時(shí)間或者滿足某些條件后,自動(dòng)跳轉(zhuǎn)到另一個(gè)目標(biāo)界面,本文小編給大家講解了Android實(shí)現(xiàn)界面的自動(dòng)跳轉(zhuǎn)功能,感興趣的小伙伴跟著小編一起來(lái)看看吧2025-04-04
Android中AutoCompleteTextView與TextWatcher結(jié)合小實(shí)例
這篇文章主要為大家詳細(xì)介紹了Android中AutoCompleteTextView與TextWatcher結(jié)合的小實(shí)例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-05-05
Android Retrofit的簡(jiǎn)單介紹和使用
這篇文章主要介紹了Android Retrofit的簡(jiǎn)單介紹和使用2017-03-03
Android?Flutter實(shí)現(xiàn)頁(yè)面切換轉(zhuǎn)場(chǎng)動(dòng)畫(huà)效果
Hero組件非常適合從列表、概覽頁(yè)切換到詳情頁(yè)轉(zhuǎn)場(chǎng)動(dòng)畫(huà)場(chǎng)合。本文將利用Hero組件制作一個(gè)簡(jiǎn)單的頁(yè)面切換轉(zhuǎn)場(chǎng)動(dòng)畫(huà)效果,感興趣的可以了解一下2022-06-06
Android中SharedPreferences簡(jiǎn)單使用實(shí)例
這篇文章主要介紹了Android中SharedPreferences簡(jiǎn)單使用案例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10
基于Socket.IO實(shí)現(xiàn)Android聊天功能代碼示例
本篇文章主要介紹了基于Socket.IO實(shí)現(xiàn)Android聊天功能代碼示例,具有一定的參考價(jià)值,有興趣的可以了解一下2017-08-08
Android getActivity()為空的問(wèn)題解決辦法
這篇文章主要介紹了Android getActivity()為空的問(wèn)題解決辦法的相關(guān)資料,導(dǎo)致apk空指針崩潰問(wèn)題,很嚴(yán)重的問(wèn)題,為了解決這問(wèn)題,上網(wǎng)搜索了很多資料,需要的朋友可以參考下2017-07-07

