app崩潰後自動重啓

android

引用:http://blog.csdn.net/caiwenfeng_for_23/article/details/41184353html

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()); //結束進程以前能夠把你程序的註銷或者退出代碼放在這段代碼以前 } }java

iOS

引用:http://blog.sina.com.cn/s/blog_b71d24920101ky2d.htmlandroid

  1. 在程序啓動時加上一個異常捕獲監聽,用來處理程序崩潰時的回調動做
    NSSetUncaughtExceptionHandler (&UncaughtExceptionHandler);
    官方文檔介紹:Sets the top-level error-handling function where you can perform last-minute logging before the program terminates.
    UncaughtExceptionHandler是一個函數指針,該函數須要咱們實現,能夠取本身想要的名字。當程序發生異常崩潰時,該函數會獲得調用,這跟C,C++中的回調函數的概念是同樣的。ios

  2. 實現本身的處理函數
    app

    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);
    }
    函數

    以上代碼很簡單,可是帶來的做用是很是大的。
相關文章
相關標籤/搜索