一个APP总会有几个我们人脑忽略掉的异常,所以就需要一个全局异常捕获,来处理这些异常,
一般使用Thread类中唯一的Interface来处理:
@FunctionalInterface
public interface UncaughtExceptionHandler {
/**
* Method invoked when the given thread terminates due to the
* given uncaught exception.
* <p>Any exception thrown by this method will be ignored by the
* Java Virtual Machine.
* @param t the thread
* @param e the exception
*/
void uncaughtException(Thread t, Throwable e);
}
直接上代码,方便以后搬砖:
package com.example.myapplication.util;
import android.content.Context;
import android.content.Intent;
import com.example.myapplication.LauncherActivity;
import java.lang.Thread.UncaughtExceptionHandler;
/**
* 自定义全局异常捕获类
*
* @author Alex
*/
public class CrashHandler implements UncaughtExceptionHandler {
private Context mContext;
private static volatile CrashHandler crashHandler;
private UncaughtExceptionHandler mDefaultHandler;
// 获取CrashHandler实例 单例模式 - 双重校验锁
public static CrashHandler getInstance() {
if (crashHandler == null) {
synchronized (CrashHandler.class) {
if (crashHandler == null) {
crashHandler = new CrashHandler();
}
}
}
return crashHandler;
}
/**
* 初始化
* @param context
*/
public void init(Context context) {
mContext = context;
// 静态方法,获取系统默认的UncaughtException处理器,对所有线程都有效
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
// 设置该CrashHandler为程序的默认处理器
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread thread, final Throwable throwable) {
if (!handleException(throwable) && mDefaultHandler != null) {
// 如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, throwable);
} else {
// 打开启动页
Intent intent = new Intent(mContext, LauncherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
// 杀死该应用进程
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
}
}
/**
* 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
*
* @param throwable
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handleException(Throwable throwable) {
if (throwable == null) {
return false;
}
// 此处 收集设备参数信息,保存日志文件
// todo
return true;
}
}
在自定义Application中初始化就可以用了:
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
CrashHandler.getInstance().init(this);
}
}
好了,又可以愉快的玩耍了。