ad.UncaughtExceptionHandler {
@Override
public void run() {
// TODO Auto-generated method stub
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread arg0, Throwable arg1) {
// TODO Auto-generated method stub
Log.i("tag", "childThread:截获到forceclose,异常原因为:" + "\n" +
arg1.toString()+" Thread->"+arg0.getId()+" 本线程id->"+Thread.currentThread().getId()+" "+
Thread.currentThread().getName());
android.os.Process.killProcess(android.os.Process.myPid());
}
}
这里有个问题:我们明明是在子线程捕获的异常,但是怎么Thread的id->1 本线程id->1,为什么线程是主线程!在下面探讨这个问题。
08-09 19:02:47.734 14483-14483/example.com.force_anr I/tag: --->>onCreate
08-09 19:02:51.304 14483-14483/example.com.force_anr I/tag: childThread:截获到forceclose,异常原因为:
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 Thread->1 本线程id->1 main
4.解决第三步的问题
我们重写子线程:在子线程里设置异常,同时别忘把activity中的捕获异常的代码和发生异常的代码删除。
class MyRunnable extends Thread implements Thread.UncaughtExceptionHandler {
int a[];
@Override
public void run() {
// TODO Auto-generated method stub
Thread.setDefaultUncaughtExceptionHandler(this);
int i = a[0];//异常
}
@Override
public void uncaughtException(Thread arg0, Throwable arg1) {
// TODO Auto-generated method stub
Log.i("tag", "childThread:截获到forceclose,异常原因为:" + "\n" +
arg1.toString()+" Thread->"+arg0.getId()+" 本线程id->"+Thread.currentThread().getId()+" "+
Thread.currentThread().getName());
android.os.Process.killProcess(android.os.Process.myPid());
}
}
在启动程序看到下面的log:
08-09 19:08:20.124 16308-16308/example.com.force_anr I/tag: --->>onCreate
08-09 19:08:20.124 16308-16341/example.com.force_anr I/tag: childThread:截获到forceclose,异常原因为:
java.lang.NullPointerException: Attempt to read from null array Thread->44829 本线程id->44829 Thread-44829
08-09 19:08:20.254 16349-16349/example.com.force_anr I/tag: --->>onCreate
08-09 19:08:20.354 16376-16376/example.com.force_anr I/tag: --->>onCreate
08-09 19:08:20.354 16376-16411/example.com.force_anr I/tag: childThread:截获到forceclose,异常原因为:
java.lang.NullPointerException: Attempt to read from null array Thread->44839 本线程id->44839 Thread-44839
好像是尝试启动了两次,看下Thread已经变了。所以在这个方法uncaughtException(Thread arg0, Throwable arg1)中的arg0指的是发生异常的那个Thread,而不一定是uncaughtException注册的Thread。