Android使用UncaughtExceptionHandler捕获全局异常
发布日期:2021-05-08 00:09:14 浏览次数:28 分类:精选文章

本文共 2644 字,大约阅读时间需要 8 分钟。

UncaughtExceptionHandler可以用来捕获程序异常,例如NullPointerException空指针异常在未被try catch捕获时,系统会弹出对话框提示“XXX程序异常退出”,给用户体验带来不良影响。为了捕获应用运行时异常并提供友好提示,我们可以通过继承UncaughtExceptionHandler类来实现。

CrashHandler类实现

我们可以创建一个CrashHandler类,继承自UncaughtExceptionHandler,来处理程序中的异常。以下是CrashHandler类的实现代码:

public class CrashHandler implements UncaughtExceptionHandler {
private static final String TAG = CrashHandler.class.getSimpleName();
private static CrashHandler instance;
private OnBeforeHandleExceptionListener mListener;
private Context context;
private Thread.UncaughtExceptionHandler defaultHandler;
private DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss.SSS", Locale.CHINA);
private CrashHandler() {
}
public static CrashHandler getInstance() {
if (instance == null) {
synchronized (CrashHandler.class) {
if (instance == null) {
instance = new CrashHandler();
}
}
}
return instance;
}
public void init(Context context) {
this.context = context;
defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (mListener != null) {
mListener.onBeforeHandleException();
}
boolean handled = handleException(ex);
if (!handled && defaultHandler != null) {
defaultHandler.uncaughtException(thread, ex);
} else {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, "error:", e);
}
Process.killProcess(MyProcess.getMyPid());
System.exit(1);
}
}
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
new Thread() {
@Override
public void run() {
Looper.prepare();
ex.printStackTrace();
String error = "[" + ex.getMessage() + "]";
Toast.makeText(context, "程序出现异常." + error, Toast.LENGTH_LONG).show();
Looper.loop();
}
}.start();
String info = collectDeviceInfo(context, ex);
saveCrashInfo2File(info);
return true;
}
}

应用绑定方法

在应用的Application或Activity的onCreate方法中,添加以下两行代码即可:

CrashHandler crashHandler = CrashHandler.getInstance();
crashHandler.init(getApplicationContext());

通过这种方式,我们可以确保程序中未被try catch捕获的异常能够被CrashHandler类所处理,并提供友好的用户提示,避免用户感到困惑或程序直接退出。

上一篇:Android基本知识
下一篇:Android开发常识

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年04月06日 18时28分50秒