Android 應(yīng)用Crash 后自動重啟的方法小結(jié)
前提
首先,我們肯定要在Application里面注冊一個(gè)CrashHandler,監(jiān)聽?wèi)?yīng)用crash
public class TestApplication extends MultiDexApplication { private static TestApplication mInstance; @Override public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(new CrashHandler()); }
然后在這個(gè)CrashHandler 想辦法重啟應(yīng)用。有兩種方法如下:
方法1.通過AlarmManager
public class CrashHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { //重啟app /** * 這種方式 功能是可以達(dá)成 * 但是有問題就是如果說你的app掛了 這時(shí)候會顯示系統(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()); }}
這個(gè)第三方庫的原理是:當(dāng)app 崩潰的時(shí)候,ProcessPhoenix.triggerRebirth(TestApplication.getInstance());就會觸發(fā)啟動另外一個(gè)進(jìn)程的Activity,然后把當(dāng)前崩潰的進(jìn)程結(jié)束掉。在新進(jìn)程的Activity里面,把應(yīng)用在自己的進(jìn)程里面的啟動起來。
總結(jié)
到此這篇關(guān)于Android 應(yīng)用Crash 后自動重啟的文章就介紹到這了,更多相關(guān)android 自動重啟內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享2. SXNA RSS Blog 聚合器程序3. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向4. XML入門的常見問題(四)5. CSS Hack大全-教你如何區(qū)分出IE6-IE10、FireFox、Chrome、Opera6. PHP設(shè)計(jì)模式中工廠模式深入詳解7. XML 增、刪、改和查示例8. ASP常用日期格式化函數(shù) FormatDate()9. 使用Spry輕松將XML數(shù)據(jù)顯示到HTML頁的方法10. webpack高級配置與優(yōu)化詳解
