UncaughtExceptionHandler
1、自 定 义 一 个 Application , 比 如 叫 MyApplication 继 承 Application 实 现UncaughtExceptionHandler。
2、覆写 UncaughtExceptionHandler 的 onCreate 和 uncaughtException 方法。
@Override
public void onCreate() super.onCreate();
Thread.setDefaultUncaughtExceptionHandler(this);}
@Override
public void uncaughtException(final Thread thread, final Throwable ex) {
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
System.out.println(Thread.currentThread());
Toast.makeText(getApplicationContext(), "thread="+thread.getId()+"ex="+ex.toString(), 1).show();、Looper.loop();
}}).start();
SystemClock.sleep(3000);
android.os.Process.killProcess(android.os.Process.myPid());}}
注意:上面的代码只是简单的将异常打印出来。在 onCreate 方法中我们给 Thread 类设置默认异常处理 handler,如果这句代码不执行则一切都是白搭。在 uncaughtException 方法中我们必须新开辟个线程进行我们异常的收集工作,然后将系统给杀死。
3.在AndroidManifest 中配置该 Application
<applicationandroid:name="com.example.uncatchexception.MyApplication"
--------------------------------------------------------------------------------