2014-05-13 83 views
1

嗨我正在處理一個第三方庫,它有時會出錯並導致重新啓動活動。有沒有一種方法可以告訴活動何時從崩潰中重新啓動?我嘗試使用這樣的未捕獲的異常處理程序,但它沒有被觸發。當一個活動從崩潰中重新啓動時捕獲

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { 
     @Override 
     public void uncaughtException(Thread thread, Throwable throwable) { 
      Log.d("un", "caught"); 
     } 
    }); 
+0

屏蔽錯誤永遠是一個壞主意。請圖書館的作者解決這些錯誤或自己修復它們。 – Karakuri

回答

1

寫這樣

Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,YOURCURRENTCLASSNAME.class)); 

而且使用這個類親愛的。我也用這個

public class MyExceptionHandler implements 
     java.lang.Thread.UncaughtExceptionHandler { 
    private final Context myContext; 
    private final Class<?> myActivityClass; 

    public MyExceptionHandler(Context context, Class<?> c) { 

     myContext = context; 
     myActivityClass = c; 
    } 

    public void uncaughtException(Thread thread, Throwable exception) { 

     StringWriter stackTrace = new StringWriter(); 
     exception.printStackTrace(new PrintWriter(stackTrace)); 
     System.err.println(stackTrace);// You can use LogCat too 
     Intent intent = new Intent(myContext, myActivityClass); 
     String s = stackTrace.toString(); 
     // you can use this String to know what caused the exception and in 
     // which Activity 
     intent.putExtra("uncaughtException", 
       "Exception is: " + stackTrace.toString()); 
     intent.putExtra("stacktrace", s); 
     myContext.startActivity(intent); 
     // for restarting the Activity 
//  Process.killProcess(Process.myPid()); 
     System.out.println("comingggggggggggggggggg in crashhhhhhhhhhhhhhhhhhhh and restrttttttttttttt autometically "); 
     Intent i = myContext.getPackageManager().getLaunchIntentForPackage(myContext.getPackageName()); 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     i.addCategory(Intent.CATEGORY_HOME); 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 
     i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     myContext.startActivity(i); 
     System.exit(0); 
    } 
} 
+0

是否有一種方法可以重寫此消息,並將消息傳遞給默認日誌貓,並顯示錯誤顏色? – user1634451

0

或者,如果你正在尋找工作,出的現成的解決方案,你可以使用bug跟蹤服務,如CrashlyticsCrittercism。他們都提供了一種方法來了解當前運行是否發生在碰撞後。

Crashlytics

Crashlytics.getInstance().setListener(new CrashlyticsListener() { 
    @Override 
    public void crashlyticsDidDetectCrashDuringPreviousExecution() { 
     // if this method is called, it means that a crash occurred 
     // in the previous run 
     didCrashOnLastLoad = true; 
    } 
}); 

Crittercismsource

CritterCallback cb = new CritterCallback() { 
    @Override public void onCritterDataReceived(CritterUserData userData) { 
     boolean crashedOnLastLoad = userData.crashedOnLastLoad(); 
     // ...do something with crashedOnLastLoad 
    } 
}; 

CritterUserDataRequest request = new CritterUserDataRequest(cb) 
           .requestDidCrashOnLastLoad(); 

// Fire off the request. 
request.makeRequest(); 
相關問題