1. 程式人生 > >app崩潰後捕獲異常或自動重啟

app崩潰後捕獲異常或自動重啟

     假如你開發的app有這個需求的話:崩潰後自動重啟或者捕獲異常資訊。你可以參照下文:

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());  //結束程序之前可以把你程式的登出或者退出程式碼放在這段程式碼之前
    }
}

這個是application級別的應用!
其實關鍵還是UncaughtExceptionHandler類!各位自己百度google了!