我發佈了簡單的solution很久以前的自定義處理Android崩潰。這是一個小黑客,但它適用於所有Android版本(包括棒棒糖)。
首先有點理論。在Android中使用未捕獲的異常處理程序時遇到的主要問題與主要(又名UI)線程中引發的異常有關。這是爲什麼。當應用程序啓動系統調用ActivityThread.main方法,準備好,開始您的應用程序的Main looper:
public static void main(String[] args) {
…
…
Looper.prepareMainLooper();
…
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
主要尺蠖是負責處理張貼在UI線程(包括與UI渲染和互動的所有消息)消息。如果在UI線程中拋出異常,它將被異常處理程序捕獲,但由於您不在loop()
方法中,因此無法向用戶顯示任何對話框或活動,因爲沒有人可以處理UI給你的消息。
建議的解決方案非常簡單。我們用我們自己的方法運行Looper.loop
方法,並用try-catch塊將其包圍。當發現異常時,我們會按照我們的要求處理它(例如,開始我們的自定義報告活動),並再次調用Looper.loop
方法。
下面的方法演示了這種方法(它應該從Application.onCreate
監聽器調用):
private void startCatcher() {
UncaughtExceptionHandler systemUncaughtHandler = Thread.getDefaultUncaughtExceptionHandler();
// the following handler is used to catch exceptions thrown in background threads
Thread.setDefaultUncaughtExceptionHandler(new UncaughtHandler(new Handler()));
while (true) {
try {
Looper.loop();
Thread.setDefaultUncaughtExceptionHandler(systemUncaughtHandler);
throw new RuntimeException("Main thread loop unexpectedly exited");
} catch (Throwable e) {
showCrashDisplayActivity(e);
}
}
}
正如你可以看到未捕獲的異常處理程序僅用於在後臺線程拋出的異常。以下處理程序捕獲的異常,並將它們傳播到UI線程:
static class UncaughtHandler implements UncaughtExceptionHandler {
private final Handler mHandler;
UncaughtHandler(Handler handler) {
mHandler = handler;
}
public void uncaughtException(Thread thread, final Throwable e) {
mHandler.post(new Runnable() {
public void run() {
throw new BackgroundException(e);
}
});
}
}
使用這種技術可以用我的GitHub庫示例項目:https://github.com/idolon-github/android-crash-catcher
能否請你分享代碼相同.. – 2012-04-20 11:11:43
如果您想記錄您的例外情況,請查看http://acra.ch/。 ACRA允許您將錯誤報告發送至Google-Doc或通過電子郵件發送給您。 – 2013-01-21 12:53:13
@Alexander或者您可以使用Google Analytics for Android,並記錄您想要的所有例外... – 2013-06-27 16:48:29