2016-02-02 25 views
0

我希望用戶能夠在服務崩潰時發送錯誤報告。我有一個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 

      } 
} 
+0

只需在'Application#onCreate'內部調用'Thread.setDefaultUncaughtExceptionHandler()',(你需要擴展'Application'類) – pskink

回答

0

documentationThread.setDefaultUncaughtExceptionHandler()表示:

這個處理器的情況下,援引任何線程終止由於 未處理的異常

你並不需要調用每個線程方法。嘗試在服務的onCreate()方法中設置默認句柄。

+0

是的,這就是我第一次嘗試的。那也行不通。我認爲它不起作用,因爲onCreate可能是一個操作系統線程(我無法在文檔中找到什麼線程調用onCreate方法)。 – Harmen

+0

嗯。我會研究更多。我認爲「任何」意味着這個過程中的每一個線程。 –

+0

是的,我認爲你對文檔的解釋是正確的。但它並沒有幫助我的問題。奇怪的是我沒有在logcat中獲得堆棧轉儲。 – Harmen