2016-02-02 24 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