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

时间:2022-02-16 21:27:16

1、实现UncaughtExceptionHandler,在方法uncaughtException中处理没有捕获的异常。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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,来捕获异常

代码:
 

?
1
2
3
4
5
6
7
8
9
10
public class MyApplication extends Application
{
  public void onCreate()
  {
    super.onCreate();
    GlobalException handler = GlobalException.getInstance();   
    Thread.setDefaultUncaughtExceptionHandler(handler);  
    
  }
}

相关文章