主要有三步
一、AndroidManifest.xml配置Application
二、在Application初始化CrashHandler(異常統一捕獲)
三、CrashHandler
要測試可以增加一個按鈕,響應“ int i = 0/0 ; ”就可以測試
一、AndroidManifest.xml
這個主要是“ android:name=".BaseApplication" ”其它代碼可以忽略
<?xml version="1.0" encoding="utf-8"?>
二、Application
import android.app.Application;
import android.content.Context;
/**
* 項目名稱:sanhemu
* 類名稱:BaseApplication
* 類描述:Application基礎類
* 創建人: wjl
* 創建時間: 2017-05-10 18:00:17
*/
public class BaseApplication extends Application {
private Context sContext;
@Override
public void onCreate() {
super.onCreate();
sContext = getApplicationContext();
initErrorHandler();//當程序出現異常後,進行重啓(需要有啓動頁才能用)
}
private void initErrorHandler(){
CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init();
crashHandler.switchCrashActivity(getContext());
}
public Context getContext() {
return sContext;
}
}
三、CrashHandler
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import java.lang.Thread.UncaughtExceptionHandler;
/**
* 項目名稱:sanhemu
* 類名稱:CrashHandler
* 類描述:異常統一捕獲
* UncaughtException處理類,當程序發生Uncaught異常的時候,
* 由該類來接管程序,並記錄發送錯誤報告.
* 需要在Application中註冊,爲了要在程序啓動器就監控整個程序。
* 創建人:wjl
* 創建時間:2017-05-10 18:05:01
*/
public class CrashHandler implements UncaughtExceptionHandler {
private static final String TAG = "CrashHandler";
// CrashHandler實例
private static CrashHandler instance;
// 程序的Context對象
private Context context;
/** 保證只有一個CrashHandler實例 */
private CrashHandler() {
}
/** 獲取CrashHandler實例 ,單例模式 */
public static CrashHandler getInstance() {
if (instance == null)
instance = new CrashHandler();
return instance;
}
/**
* 初始化
*/
public void init() {
// 設置該CrashHandler爲程序的默認處理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
/*
* 切換髮生Crash所在的Activity
*/
public void switchCrashActivity(Context context) {
this.context = context;
}
/**
* 當UncaughtException發生時會轉入該函數來處理(當應用出現異常後進行重啓應用)
*/
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// 使用Toast來顯示異常信息
new Thread() {
@Override
public void run() {
Looper.prepare();
Toast.makeText(context, "很抱歉,程序出現異常,3秒後將重啓.",
Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
try {
Thread.sleep(3000);
restartApp();
} catch (InterruptedException e) {
Log.e(TAG, "error : ", e);
}
}
private void restartApp(){
//有“_”是因爲項目有備置androidannotations,如果“MainActivity_.class”不正確,程序會一直卡住
Intent intent = new Intent(context,MainActivity_.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
android.os.Process.killProcess(android.os.Process.myPid()); //結束進程之前可以把你程序的註銷或者退出代碼放在這段代碼之前
}
}