開發(fā)中,我們時常會遇到各種各樣的崩潰問題,對于這種問題,我們的做法是try掉,讓android自帶的類UncaughtExceptionHandler捕獲日志.但是對于這種捕獲,不會顯示到手機上,對于后期的維護是一大問題.于是我們就有了自定義該類的做法,捕獲錯誤日志,讓錯誤日志生成文件的形式保存到手機和上傳到服務器.
于是我就寫了一個捕獲日志的工具類: CrashHandlerUtils.java
使用方式需要在Application中申明,初始化
CrashHandlerUtils.getInstance().init(getApplicationContext());
默認名稱是 crachLog.創(chuàng)建默認文件夾下
或者
CrashHandlerUtils.getInstance().init(getApplicationContext(),"名稱");
代碼如下:
UncaughtException處理類,當程序發(fā)生Uncaught異常的時候,有該類來接管程序,并錄錯誤報告.
需要在Application中注冊,為了要在程序啟動時就監(jiān)控整個程序懂盐。
package com.isoftstone.randomchoose.utils;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* UncaughtException處理類,當程序發(fā)生Uncaught異常的時候,有該類來接管程序,并記錄錯誤報告.
* 需要在Application中注冊嘱朽,為了要在程序啟動時就監(jiān)控整個程序。
*/
public class CrashHandlerUtils implements UncaughtExceptionHandler {
public static final String TAG = "CrashHandler";
//系統(tǒng)默認的UncaughtException處理類
private UncaughtExceptionHandler mDefaultHandler;
//CrashHandler實例
private static CrashHandlerUtils instance;
//程序的Context對象
private Context mContext;
//用來存儲設備信息和異常信息
private Map<String, String> infos = new HashMap<String, String>();
//用于格式化日期,作為日志文件名的一部分
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//設置保存目錄
private String name = "crachLog";
/**
* 保證只有一個CrashHandler實例
*/
private CrashHandlerUtils() {
}
/**
* 獲取CrashHandler實例 ,單例模式
*/
public static CrashHandlerUtils getInstance() {
if (instance == null)
instance = new CrashHandlerUtils();
return instance;
}
/**
* 初始化
**/
public void init(Context context) {
mContext = context;
//獲取系統(tǒng)默認的UncaughtException處理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
//設置該CrashHandler為程序的默認處理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
/**
* 初始化
**/
public void init(Context context,String dec) {
init(context);
this.name = dec;
}
/**
* 當UncaughtException發(fā)生時會轉入該函數(shù)來處理
**/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
//如果用戶沒有處理則讓系統(tǒng)默認的異常處理器來處理
mDefaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
//退出程序
// 關閉并重啟應用
System.gc();
_restart();
android.os.Process.killProcess(android.os.Process.myPid());
// android.os.Process.killProcess(android.os.Process.myPid());
// System.exit(1);//0表示正常退出,非0表示非正常退出
}
}
/** 重啟應用 */
public void _restart() {
Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
/**
* 自定義錯誤處理,收集錯誤信息 發(fā)送錯誤報告等操作均在此完成.
*
* @param ex
* @return true:如果處理了該異常信息;否則返回false.
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
//收集設備參數(shù)信息
collectDeviceInfo(mContext);
//使用Toast來顯示異常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(mContext, "很抱歉,程序出現(xiàn)異常,即將退出.", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
//保存日志文件
saveCatchInfo2File(ex);
return true;
}
/**
* 收集設備參數(shù)信息
*
* @param ctx
*/
public void collectDeviceInfo(Context ctx) {
try {
PackageManager pm = ctx.getPackageManager();
PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
if (pi != null) {
String versionName = pi.versionName == null ? "null" : pi.versionName;
String versionCode = pi.versionCode + "";
infos.put("versionName", versionName);
infos.put("versionCode", versionCode);
}
} catch (NameNotFoundException e) {
Log.e(TAG, "an error occured when collect package info", e);
}
Field[] fields = Build.class.getDeclaredFields();
for (Field field : fields) {
try {
field.setAccessible(true);
infos.put(field.getName(), field.get(null).toString());
Log.d(TAG, field.getName() + " : " + field.get(null));
} catch (Exception e) {
Log.e(TAG, "an error occured when collect crash info", e);
}
}
}
/**
* 獲取存儲路徑
**/
private String getFilePath() {
String file_dir = "";
// SD卡是否存在
boolean isSDCardExist = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
// Environment.getExternalStorageDirectory()相當于File file=new File("/sdcard")
//boolean isRootDirExist = Environment.getExternalStorageDirectory().exists();
if (isSDCardExist) {
file_dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+name+"/";
} else {
// MyApplication.getInstance().getFilesDir()返回的路勁為/data/data/PACKAGE_NAME/files踏堡,其中的包就是我們建立的主Activity所在的包
// getRootDirectory是/system碌燕,即系統(tǒng)文件夾,要root了才看得到
file_dir = Environment.getRootDirectory().getAbsolutePath() + "/"+name+"/";
}
return file_dir;
}
/**
* 保存錯誤信息到文件中
*
* @param ex
* @return 返回文件名稱, 便于將文件傳送到服務器
*/
private String saveCatchInfo2File(Throwable ex) {
StringBuffer sb = new StringBuffer();
for (Map.Entry<String, String> entry : infos.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key + "=" + value + "\n");
}
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
ex.printStackTrace(printWriter);
Throwable cause = ex.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String result = writer.toString();
sb.append(result);
try {
String time = formatter.format(new Date());
String fileName = "crash-" + time + ".txt";
//獲取外部存儲的路徑倔幼,如果直接在該路徑下創(chuàng)建的文件夾或文件盖腿,是沒有與應用關聯(lián)的
// 即使應用卸載,遺留下的文件夾或文件仍然存在
//String file_dir = getFilePath();
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
// getExternalFilesDir("文件夾名"),則是創(chuàng)建應用私有文件夾翩腐,在Android/data/包名/files/文件夾名
File file = new File(mContext.getExternalFilesDir("crashlog"), fileName);
Log.e(TAG, "崩潰日志:" + file.getAbsolutePath());
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
FileOutputStream fos = new FileOutputStream(file);
fos.write(sb.toString().getBytes());
fos.close();
}
}
return fileName;
} catch (Exception e) {
Log.e(TAG, "an error occured while writing file...", e);
}
return null;
}
}
常用工具類地址,在github上utils里面
戳我跳轉 ------ https://github.com/Simonhy
歡迎評論和贊賞,喜歡的話收藏一下.對于上傳到服務器的操作,推薦一篇
https://juejin.im/post/59342ddd0ce46300571d95b5
寫的比較詳細,
歡迎轉載!!!
歡迎轉載!!!
歡迎轉載!!!