我希望用戶能夠在服務崩潰時發送錯誤報告。我有一個GUI應用程序,它使用服務中的廣播進行更新。該服務在不同的進程中運行,並以前臺運行。我使用相同的代碼來將缺省異常處理程序附加到我的GUI,並且它工作正常(打開電子郵件發送應用程序,電子郵件正文包含異常)。但是對於我的服務線程,我無法讓他們調用UncaughtExceptionHandler。服務默認異常處理程序不工作(threadID已更改)
我到目前爲止所做的研究是,崩潰的線程與我註冊cutom exceptionhandler(229)的線程有不同的線程(12)註冊和崩潰在同一個Timer_Tick中可運行,並且應該有同一個threadid。
logcat的輸出:
> D/Registratie: General exception handler set for threadid=229
> D/Registratie: ThreadName in Timer_Tick: Timer-0 threadId=229
> D/Registratie: ThreadName in Timer_Tick: Timer-0 threadId=229
> D/Registratie: ThreadName in Timer_Tick: Timer-0 threadId=229
> D/Registratie: Throw ArrayIndexOutOfBounds exception W/dalvikvm:
> threadid=12: thread exiting with uncaught exception (group=0x4169fba8)
服務構件和方法:
// declared non-anonymous to prevent the garbage collector erroneously clearing
private Thread.UncaughtExceptionHandler mUEHandler;
public void attachGeneralExceptionHandler(){
mUEHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
Log.d(TAG, "Custom crash handler: build crashrapport and intent");
sendExceptionReport(t,e);
mUEHandler.uncaughtException(t, e);
}
};
Thread.setDefaultUncaughtExceptionHandler(mUEHandler);
Log.d(TAG, "General exception handler set for ThreadName: " + Thread.currentThread().getName() + " threadid=" + Thread.currentThread().getId());
}
從服務TimerTick:
private Runnable Timer_Tick = new Runnable() {
public void run() {
if(!uncaughtExceptionHandlerSet) {
// Make sure the exception handler is connected to this Timer_Tick thread
attachGeneralExceptionHandler();
uncaughtExceptionHandlerSet=true;
}
Log.d(TAG, "ThreadName in Timer_Tick: "+ Thread.currentThread().getName()+" threadId="+Thread.currentThread().getId());
if(testExceptionHandling){
Log.d("TAG", "Throw ArrayIndexOutOfBounds exception");
int[] exceptionTest = new int[3];
exceptionTest[3] = -1; // throws exception on thread with threadid 12, only one line in logcat
}
}
只需在'Application#onCreate'內部調用'Thread.setDefaultUncaughtExceptionHandler()',(你需要擴展'Application'類) – pskink