public class CrashHandler implements Thread.UncaughtExceptionHandler { public static CrashHandler mAppCrashHandler; private Thread.UncaughtExceptionHandler mDefaultHandler; private MyApplication mAppContext; public void initCrashHandler(MyApplication application) { this.mAppContext = application; // 獲取系統默認的UncaughtException處理器 mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler(); Thread.setDefaultUncaughtExceptionHandler(this); } public static CrashHandler getInstance() { if (mAppCrashHandler == null) { mAppCrashHandler = new CrashHandler(); } return mAppCrashHandler; } @Override public void uncaughtException(Thread thread, Throwable ex) { if (!handleException(ex) && mDefaultHandler != null) { // 如果用戶沒有處理則讓系統默認的異常處理器來處理 mDefaultHandler.uncaughtException(thread, ex); } else { AlarmManager mgr = (AlarmManager) mAppContext.getSystemService(Context.ALARM_SERVICE); Intent intent = new Intent(mAppContext, WelcomeActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("crash", true); PendingIntent restartIntent = PendingIntent.getActivity(mAppContext, 0, intent, PendingIntent.FLAG_ONE_SHOT); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒鐘後重啓應用 android.os.Process.killProcess(android.os.Process.myPid()); System.exit(0); System.gc(); } } /** * 錯誤處理,收集錯誤信息 發送錯誤報告等操作均在此完成. * @param ex * @return true:如果處理了該異常信息;否則返回false. */ private boolean handleException(Throwable ex) { if (ex == null) { return false; } // 自定義處理錯誤信息 return true; } }
程序崩潰處理
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.