【Android 優(yōu)化 處理全局未捕獲異常,并重啟應用】
1、創(chuàng)建一個CrashHandler類
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static final String TAG = CrashHandler.class.getSimpleName();
private static CrashHandler instance; // 單例模式
private Context context; // 程序Context對象
private Thread.UncaughtExceptionHandler defalutHandler; // 系統(tǒng)默認的UncaughtException處理類
private CrashHandler() {
}
/** 獲取CrashHandler實例 */
public static CrashHandler getInstance() {
if (instance == null) {
synchronized (CrashHandler.class) {
if (instance == null) {
instance = new CrashHandler();
}
}
}
return instance;
}
/** 異常處理初始化 */
public void init(Context context) {
this.context = context;
// 獲取系統(tǒng)默認的UncaughtException處理器
defalutHandler = Thread.getDefaultUncaughtExceptionHandler();
// 設置該CrashHandler為程序的默認處理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
/** 當UncaughtException發(fā)生時會轉入該函數(shù)來處理 */
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// 自定義錯誤處理
boolean res = handleException(ex);
if (!res && defalutHandler != null) {
// 如果用戶沒有處理則讓系統(tǒng)默認的異常處理器來處理
defalutHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(1500);//1.5秒后關閉并重啟應用
} catch (InterruptedException e) {
LogUtil.e(TAG, "error : ", e);
}
// 關閉并重啟應用
System.gc();
_restart();
android.os.Process.killProcess(android.os.Process.myPid());
}
}
/** 重啟應用 */
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(final Throwable ex) {
if (ex == null) {
return false;
}
new Thread() {
@Override
public void run() {
Looper.prepare();
ex.printStackTrace();
ToastUtils.showToast("應用出現(xiàn)異常,即將重啟");
Looper.loop();
}
}.start();
// 收集設備參數(shù)信息 \日志信息
return true;
}
}
2、在Application的onCreate()里實例化該crashHandler
public class MyApplication extends MultiDexApplication {
@Override
public void onCreate() {
super.onCreate();
...
CrashHandler.getInstance().init(this);
...
}
}
引用:
62、在app遇到全局異常時避免直接退出,如何讓app接管異常處理?