首页 > 系统 > Android > 正文

Android中捕获全局异常实现代码

2020-04-11 11:34:47
字体:
来源:转载
供稿:网友

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);         }}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表