我希望用户能够在服务崩溃时发送错误报告。我有一个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