使用CrashHandler獲取應用crash資訊
- 2020 年 8 月 19 日
- 筆記
Android應用不可避免會發生crash,也稱之為崩潰。發生原因可能是由於Android系統底層的bug,也可能是由於不充分的機型適配或者是糟糕的網路情況。當crash發生時,系統會kill掉正在執行的程式,現象就是閃退或者提示用戶程式已停止運行。更糟糕的是,當用戶發生了crash,開發者卻無法得知程式為何crash,因此需要知道用戶當時的crash資訊。為此Android提供了處理這類問題的方法,即Thread類中的一個方法setDefaultUncaughtExceptionHandler
:
/**
* Sets the default uncaught exception handler.
* This handler is invoked in case any Thread due to unhandled exception.
*
* @param handler
* The handler to set or null.
*/
public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler handler){
Thread.defaultUncaughtHandler = handler;
}
當crash發生的時候,系統就會回調UncaughtExceptionHandler的uncaughtException方法,在uncaughtException方法中就可以獲取到異常資訊。
下面是一個典型的異常處理器的實現:
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static final String TAG = "CrashHandler";
private static final boolean DEBUG = true;
private static final String PATH = Environment.getExternalStorageDirectory().getPath() + "/CrashTest/log/";
private static final String FILE_NAME = "crash";
private static final String FILE_NAME_SUFFIX = ".trace";
private static CrashHandler sInstance = new CrashHandler();
private Thread.UncaughtExceptionHandler mDefaultCrashHandler;
private Context mContext;
private CrashHandler(){
}
public static CrashHandler getInstance(){
return sInstance;
}
public void init(Context context){
mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
mContext = context.getApplicationContext();
}
/**
* 這個是最關鍵的函數,當程式中有未被捕獲的異常,系統將會自動調用#uncaught-
* thread為出現未捕獲異常的執行緒,ex為未捕獲的異常,有了這個ex,就可以得到異常資訊
*/
@Override
public void uncaughtException(Thread thread, Throwable ex){
try{
//導入異常資訊到SD卡中
dumpExceptionToSDCard(ex);
//這裡可以上傳異常資訊到伺服器,便於開發人員分析日誌從而解決bug
uploadExceptionToServer();
}catch(IOException e){
e.printStackTrace();
}
ex.printStackTrace();
//如果系統提供了默認的異常處理器,則交給系統去結束程式,否則就由自己結束自己
if(mDefaultCrashHandler != null){
mDefaultCrashHandler.uncaughtException(thread, ex);
}else{
android.os.Process.killProcess(android.os.Process.myPid());
}
}
private void dumpExceptionToSDCard(Throwable ex) throws IOException{
//如果SD卡不存在或無法使用,則無法把異常資訊寫入SD卡
if(!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
if(DEBUG){
Log.w(TAG, "sdcard unmounted,skip dump exception");
return;
}
}
File dir = new File(PATH);
if(!dir.exists()){
dir.mkdirs();
}
long current = System.currentTimeMillis();
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(current));
File file = new File(PATH + FILE_NAME + time + FILE_NAME_SUFFIX);
try{
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
pw.println(time);
dumpPhoneInfo(pw);
pw.println();
ex.printStackTrace(pw);
pw.close();
}catch(Exception e){
Log.e(TAG, "dump crash info failing");
}
}
private void dumpPhoneInfo(PrintWriter pw)throws PackageManager.NameNotFoundException{
PackageManager pm = mContext.getPackageManager();
PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
pw.print("APP Version: ");
pw.print(pi.versionName);
pw.print('_');
pw.println(pi.versionCode);
//Android版本號
pw.print("OS Version: ");
pw.print(Build.VERSION.RELEASE);
pw.print('_');
pw.println(Build.VERSION.SDK_INT);
//手機製造商
pw.print("Vendor: ");
pw.println(Build.MANUFACTURER);
//手機型號
pw.print("Model: ");
pw.println(Build.MODEL);
//CPU架構
pw.print("CPU ABI: ");
pw.println(Build.CPU_ABI);
}
private void uploadExceptionToServer(){
//TODO Upload Exception Message To Web Server
}
}
上面的CrashHandler使用也很簡單,可以選擇在Application初始化的時候為執行緒設置CrashHandler,如下所示:
public class MainApplication extends MultiDexApplication {
private static MainApplication sInstance;
@Override
public void onCreate() {
super.onCreate();
sInstance = this;
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(this);
}
public static MainApplication getInstance(){
return sInstance;
}