Android中捕获全局异常实现代码
1、实现UncaughtExceptionHandler,在方法uncaughtException中处理没有捕获的异常。
publicclassGlobalExceptionimplementsUncaughtExceptionHandler
{
privatefinalstaticGlobalExceptionmyCrashHandler=newGlobalException();
privateGlobalException()
{
}
publicstaticsynchronizedGlobalExceptiongetInstance()
{
returnmyCrashHandler;
}
publicvoiduncaughtException(Threadarg0,Throwablearg1)
{
Trace.Log("-------------caughtException--");
}
}
2、继承Application,在其中调用Thread方法setDefaultUncaughtExceptionHandler,来捕获异常
代码:
publicclassMyApplicationextendsApplication
{
publicvoidonCreate()
{
super.onCreate();
GlobalExceptionhandler=GlobalException.getInstance();
Thread.setDefaultUncaughtExceptionHandler(handler);
}
}