安卓全域性異常捕捉
阿新 • • 發佈:2019-01-02
直接上程式碼就是幹
public class ExceptionCapture implements Thread.UncaughtExceptionHandler {
private static ExceptionCapture exceptionCapture;
private Context context;
private Thread.UncaughtExceptionHandler defaultExceptionHander;
public ExceptionCapture() {
}
public static ExceptionCapture getInstance (){
if(exceptionCapture == null){
synchronized (ExceptionCapture.class){
if(exceptionCapture == null){
exceptionCapture=new ExceptionCapture();
}
}
}
return exceptionCapture;
}
/**
* 替換預設的異常捕獲類
* @param context
*/
public void init(Context context){
this.context=context;
defaultExceptionHander=Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
if (!handleEcxception(e)&&defaultExceptionHander!=null){
//未處理交由系統處理
defaultExceptionHander.uncaughtException(t,e);
}else {
//已處理結束程序
Process.killProcess(Process.myPid());
System.exit(1);
}
}
private boolean handleEcxception(Throwable ex){
if(ex == null){
return false;
}
//記錄裝置資訊,異常
SaveDeviceInfo(ex);
return true;
}
private void SaveDeviceInfo(Throwable ex) {
//獲取異常型別
String info=ex.toString();
Log.e("info","-->"+info);
StackTraceElement[] stackTraceElement=ex.getStackTrace();
//獲取異常具體傳送行號
for (StackTraceElement error:stackTraceElement) {
Log.e("error","-->"+error.toString());
}
//獲取裝置資訊,系統版本,手機品牌
String brand=Build.BRAND; //品牌
String model=Build.MODEL; //型號
int SDK=Build.VERSION.SDK_INT; //獲取系統版本
Log.e("INFO","brand:"+brand+" model:"+model+" SDK:"+SDK);
//這兒自己儲存相關異常資訊/傳送異常到後臺伺服器
}
}
好了異常捕捉類定義完成,只要在Application中初始化就可以了
ExceptionCapture exceptionCapture=ExceptionCapture.getInstance();
exceptionCapture.init(this);
這樣就可以捕捉全域性異常了