android中全局异常捕捉

时间:2021-08-15 06:50:08

android中全局异常捕捉

只要写代码就会有bug,但是我们要想办法收集到客户的bug。有第三方bugly或者友盟等可以收集。但是,android原生就提供了有关收集异常的api,所以我们来学习一下。

异常捕捉实现

android中提供了Thread.UncaughtExceptionHandler类

1.创建Thread.UncaughtExceptionHandler对象

创建对象,实现uncaughtException方法,此方法可以接收到所有异常,要做的就是对异常进行处理。

一般是对错误日志进行本地化,并且杀掉进程

Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
//处理错误日志,此段代码是将错误日志,写入本地
writeErrorLog(ex);
Log.e(TAG, ex.getMessage(), ex);
ToastUtils.longMsg(ex.getMessage());
} finally {
//杀掉应用程序
// Try everything to make sure this process goes away.
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(10);
}
}
};

2.将自定义的handler对象设置给系统

Thread.setDefaultUncaughtExceptionHandler(handler);

3.一般情况,对异常的全局处理,会在application中进行

每个应用都会创建自己的application,具体创建就不细说了

将错误日志写到本地

/**
* 打印错误日志到日志文件中
*
* @param ex Exception
*/
public void writeErrorLog(final Throwable ex) {
File dir = StorageHelper.getInstance().getLogPath();
File file = new File(dir, String.format("%s.txt", getCurrentDateString()));
Log.d(TAG, "======" + dir.getAbsolutePath()); PrintStream printStream = null;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file, true);
printStream = new PrintStream(fileOutputStream); /**
* 添加:出错的时间,设备号,安卓版本,App版本
*/
printStream.append("系统时间:").append(DateUtils.getCurrentTime(DateUtils.FORMAT_DATETIME));
printStream.append("\n设备类型:").append(DeviceUtils.getDeviceName());
printStream.append("\n设备号:").append(DeviceUtils.getUUID(EChatApp.getInstance()));
printStream.append("\nAndroid版本:").append(DeviceUtils.getReleaseVersion());
printStream.append("\nApp版本:").append(getVersion()).append("\n"); ex.printStackTrace(printStream);
fileOutputStream.close();
fileOutputStream = null;
} catch (Exception e) {
EMLog.e(TAG, e.getMessage(), e);
} finally {
IOUtils.closeQuietly(printStream);
IOUtils.closeQuietly(fileOutputStream);
}
}

ok。就介样了。