app崩溃后自动重启
android
引用:http://blog.csdn.net/caiwenfeng_for_23/article/details/41184353
package com.tan.abnormalrestart; import java.lang.Thread.UncaughtExceptionHandler; import android.app.Application; import android.content.Intent; public class AppContext extends Application { protected static AppContext instance; public void onCreate() { super.onCreate(); instance = this; Thread.setDefaultUncaughtExceptionHandler(restartHandler); // 程序崩潰時觸發線程 以下用來捕獲程序崩潰異常 } // 創建服務用于捕獲崩潰異常 private UncaughtExceptionHandler restartHandler = new UncaughtExceptionHandler() { public void uncaughtException(Thread thread, Throwable ex) { restartApp();//發生崩潰異常時,重啟應用 } }; public void restartApp(){ Intent intent = new Intent(instance,MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); instance.startActivity(intent); android.os.Process.killProcess(android.os.Process.myPid()); //結束進程之前可以把你程序的注銷或者退出代碼放在這段代碼之前 } }
iOS
引用:http://blog.sina.com.cn/s/blog_b71d24920101ky2d.html
在程序啟動時加上一個異常捕獲監聽,用來處理程序崩潰時的回調動作
NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
官方文檔介紹:Sets the top-level error-handling function where you can perform last-minute logging before the program terminates.
UncaughtExceptionHandler是一個函數指針,該函數需要我們實現,可以取自己想要的名字。當程序發生異常崩潰時,該函數會得到調用,這跟C,C++中的回調函數的概念是一樣的。
實現自己的處理函數
void UncaughtExceptionHandler(NSException exception)
{
NSArray arr = [exception callStackSymbols];//得到當前調用棧信息
NSString reason = [exception reason];//非常重要,就是崩潰的原因
NSString name = [exception name];//異常類型
NSLog(@"exception type : %@ \n crash reason : %@ \n call stack info : %@", name, reason, arr);
}
以上代碼很簡單,但是帶來的作用是非常大的。
轉載于:https://www.cnblogs.com/gamesacer/p/7644546.html
總結
以上是生活随笔為你收集整理的app崩溃后自动重启的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 全栈工程师之路-中级篇之小程序开发-第二
- 下一篇: 51Nod 1179 最大的最大公约数