Android中捕获全局异常实现代码
内容摘要
1、实现UncaughtExceptionHandler,在方法uncaughtException中处理没有捕获的异常。
public class GlobalException implements UncaughtExceptionHandler
{
private fi
public class GlobalException implements UncaughtExceptionHandler
{
private fi
文章正文
1、实现UncaughtExceptionHandler,在方法uncaughtException中处理没有捕获的异常。
public class GlobalException implements UncaughtExceptionHandler { private final static GlobalException myCrashHandler = new GlobalException(); private GlobalException() { } public static synchronized GlobalException getInstance() { return myCrashHandler; } public void uncaughtException(Thread arg0, Throwable arg1) { Trace.Log("-------------caught Exception--"); } }
2、继承Application ,在其中调用Thread方法setDefaultUncaughtExceptionHandler,来捕获异常
代码:
public class MyApplication extends Application { public void onCreate() { super.onCreate(); GlobalException handler = GlobalException.getInstance(); Thread.setDefaultUncaughtExceptionHandler(handler); } }
代码注释