Android 應用Crash 後自動重啓

前提

首先,我們肯定要在Application裏面註冊一個CrashHandler,監聽應用crash

public class TestApplication extends MultiDexApplication {
    private static TestApplication mInstance;
    @Override
    public void onCreate() {
        super.onCreate();
        Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
          }

然後在這個CrashHandler 想辦法重啓應用。有兩種方法如下:

方法1.通過AlarmManager

      public class CrashHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {

        //重啓app
        /**
         * 這種方式 功能是可以達成
         * 但是有問題就是如果說你的app掛了 這時候會顯示系統桌面
         * 然後你的app有啓動起來了
         * 給人的感覺不太好
         */
        Intent intent = new Intent();
        Context context = TestApplication.getInstance();
        intent.setClass(context, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,PendingIntent.FLAG_ONE_SHOT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC,System.currentTimeMillis() + 100,pendingIntent);
        Process.killProcess(Process.myPid());
        System.exit(0);

    }
}

方法2:

使用第三方庫

    implementation 'com.jakewharton:process-phoenix:2.0.0'

public class CrashHandler implements Thread.UncaughtExceptionHandler {
    @Override
    public void uncaughtException(Thread t, Throwable e) {

        ProcessPhoenix.triggerRebirth(TestApplication.getInstance());
    }
}


這個第三方庫的原理是:
當app 崩潰的時候,ProcessPhoenix.triggerRebirth(TestApplication.getInstance());就會觸發啓動另外一個進程的Activity,然後把當前崩潰的進程結束掉。在新進程的Activity裏面,把應用在自己的進程裏面的啓動起來。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章