Android 應用Crash 后自動重啟的方法小結
前提
首先,我們肯定要在Application里面注冊一個CrashHandler,監(jiān)聽應用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掛了 這時候會顯示系統(tǒng)桌面
* 然后你的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());就會觸發(fā)啟動另外一個進程的Activity,然后把當前崩潰的進程結束掉。在新進程的Activity里面,把應用在自己的進程里面的啟動起來。
總結
到此這篇關于Android 應用Crash 后自動重啟的文章就介紹到這了,更多相關android 自動重啟內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Kotlin結合Rxjava+Retrofit實現(xiàn)極簡網(wǎng)絡請求的方法
這篇文章主要給大家介紹了關于Kotlin結合Rxjava+Retrofit實現(xiàn)極簡網(wǎng)絡請求的相關內(nèi)容,文中分別對Rxjava和Retrofit進行了簡單的介紹,然后通過示例代碼詳細介紹了如何實現(xiàn)極簡網(wǎng)絡請求,需要的朋友可以參考借鑒,下面來一起看看吧。2017-11-11
Android之Intent附加數(shù)據(jù)的兩種實現(xiàn)方法
這篇文章主要介紹了Android之Intent附加數(shù)據(jù)的兩種實現(xiàn)方法,以實例形式較為詳細的分析了添加數(shù)據(jù)到Intent的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09
Android利用BitMap獲得圖片像素數(shù)據(jù)的方法
這篇文章主要介紹了Android利用BitMap獲得圖片像素數(shù)據(jù)的方法,結合實例對比分析了Android獲取圖片像素數(shù)據(jù)的相關技巧,需要的朋友可以參考下2016-02-02
Android 優(yōu)化之a(chǎn)pp啟動優(yōu)化的實現(xiàn)
這篇文章主要介紹了Android 優(yōu)化之啟動優(yōu)化的實現(xiàn),啟動分為冷啟動和熱啟動,溫啟動,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07

