捕获异常

/**
* UncaughtExceptionHandler一旦出现未捕获异常,就会调用如下的回调方法
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static CrashHandler crashHandler = null;
//系统默认的处理未捕获异常的处理器
private Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;
private CrashHandler(){
}
//懒汉式实现单例
public static CrashHandler getInstance(){
if(crashHandler == null){
crashHandler = new CrashHandler();
}
return crashHandler;
}
public void init(){
this.defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
//将当前类设置为出现未捕获异常的处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
//异常信息发生时的处理:可以考虑发送给服务器
@Override
public void uncaughtException(Thread thread, Throwable ex) {
// Log.e("TAG", "出现了异常!");
if(ex == null){
defaultUncaughtExceptionHandler.uncaughtException(thread,ex);
}else{
handleException(thread, ex);
}
}private void handleException(Thread thread, Throwable ex) {
//必须在主线程执行Toast
new Thread(){
public void run(){
//Android系统当中,默认情况下,线程是没有开启looper消息处理的,但是主线程除外
Looper.prepare();
Toast.makeText(UIUtils.getContext(), "亲,出现异常了!", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}.start();
//搜集异常信息
collectionException(ex);
try {
//关闭资源
thread.sleep(2000);
//移除当前activity
ActivityManager.getInstance().removeCurrent();
//结束当前进程
android.os.Process.killProcess(android.os.Process.myPid());
////关闭虚拟机,释放所有内存:参数0代表正常退出
System.exit(0);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void collectionException(Throwable ex) {
//手机手机的系统信息
final String deviceInfo = Build.DEVICE + ":" + Build.VERSION.SDK_INT + ":" + Build.MODEL + ":" + Build.PRODUCT;
final String message = ex.getMessage();
new Thread(){
public void run(){
//可以通过联网将信息发送给后台,所以在分线程执行
Log.e("TAG", "deviceInfo:" + deviceInfo + ",message:" + message);
}
}.start();
}}