在Android开发过程中,如果有Crash,我们往往想看到具体Crash的情景,但是在发布版本后,应用万一出现崩溃现象,就会出现一个弹窗说应用崩溃了,如果给用户看到,会有很大不良印象,如果是我,我觉得这个App很low。因此,我们需要一种方案来规避这个万一出现的尴尬现象。
UncaughtExceptionHandler是为了捕获没有被捕获的异常,包括运行时异常,执行错误(内存溢出等),子线程抛出的异常等,使用这个就可以捕获Crash的异常,然后自己作一些处理:
public class CrashHandler implements Thread.UncaughtExceptionHandler {
public static CrashHandler mAppCrashHandler;
private Thread.UncaughtExceptionHandler mDefaultHandler;
private MyApplication mAppContext;
public void initCrashHandler(MyApplication application) {
this.mAppContext = application;
// 获取系统默认的UncaughtException处理器
mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
public static CrashHandler getInstance() {
if (mAppCrashHandler == null) {
mAppCrashHandler = new CrashHandler();
}
return mAppCrashHandler;
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
// 如果用户没有处理则让系统默认的异常处理器来处理
mDefaultHandler.uncaughtException(thread, ex);
} else {
AlarmManager mgr = (AlarmManager) mAppContext.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(mAppContext, WelcomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("crash", true);
PendingIntent restartIntent = PendingIntent.getActivity(mAppContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
System.gc();
}
}
/**
* 错误处理,收集错误信息 发送错误报告等操作均在此完成.
* @param ex
* @return true:如果处理了该异常信息;否则返回false.
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
// 自定义处理错误信息
return true;
}
}
一般的话,只要在自己的Application中初始化一下就好了:
CrashHandler.getInstance().initCrashHandler(this);
这样用户就不会看到Crash情况,只会看到应用重启了下,这样用户体验会好些。