使用Android提供的Thread.UncaughtExceptionHandler类,可以捕获系统的unchecked exception,并提供相应的错误处理操作,增加程序的健壮性。
一个简单的示例:
public class CrashHandle implements Thread.UncaughtExceptionHandler {
private static CrashHandle Instance = new CrashHandle();
private Context context;
private Thread.UncaughtExceptionHandler DefeaultHandler;
private CrashHandle(){}
//单例模式
public static CrashHandle getInstance(){
return Instance;
}
public void init(Context context){
this.context = context;
DefeaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// TODO Auto-generated method stub
if((!HandlerException(ex)) && (this.DefeaultHandler != null)){
this.DefeaultHandler.uncaughtException(thread, ex);
}else{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Process.killProcess(Process.myPid());
System.exit(1);
}
}
//自定义错误处理,收集错误信息与发送错误信息
public boolean HandlerException(Throwable ex){
if(ex == null){
return false;
}
new Thread(){
public void run(){
Looper.prepare();
Toast.makeText(context, "程序崩溃了,即将退出", 0).show();
Looper.loop();
}
}.start();
return true;
}
}
因为Android程序的入口是application,为了使用该方法,我们需要继承Android的application类,在oncreat()方法初始化改类。
public class MyApplication extends Application{
private static MyApplication myApplication;
public void onCreate(){
super.onCreate();
CrashHandle crash = CrashHandle.getInstance();
crash.init(getApplicationContext());
}
public static MyApplication getMyApplication(){
if(myApplication == null){
myApplication = new MyApplication();
}
return myApplication;
}
}
最后,在manifest里完成注册:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name="com.zl.crash.MyApplication"/>
在mainactivity里制造一个unchecked exception,会看到如下效果: