UncaughtExceptionHandler是全局捕获异常的,为app意外中止的提供一些处理的方法。只需要实现UncaughtExceptionHandler,重写一些方法,就可以做到把异常信息保存在本地或者上传到服务器。
https://blog.csdn.net/qdjdeveloper/article/details/78130226
1、定义java类实现系统接口UncaughtExceptionHandler,具体代码如下:
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Environment;
import android.os.SystemClock;
import com.blankj.utilcode.util.TimeUtils;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Date;
/**
* Created by wyn on 2018/9/29.
*/
public class CrashHandler implements Thread.UncaughtExceptionHandler {
//文件夹目录
private static final StringPATH = Environment.getExternalStorageDirectory().getPath() +"/projectName/crash_log/";
//文件名
private static final StringFILE_NAME ="crash";
//文件名后缀
private static final StringFILE_NAME_SUFFIX =".txt";
//上下文
private ContextmContext;
private static class CrashHandlerInstance {
private static final CrashHandlerINSTANCE =new CrashHandler();
}
private CrashHandler() {
}
public static CrashHandler getInstance() {
return CrashHandlerInstance.INSTANCE;
}
@Override
public void uncaughtException(Thread t, Throwable e) {
//导出异常信息到SD卡
dumpExceptionToSDCard(e);
//上传异常信息到服务器
uploadExceptionToServer(e);
//延时1秒杀死进程
SystemClock.sleep(2000);
android.os.Process.killProcess(android.os.Process.myPid());
}
public void init(Context context) {
//将当前实例设为系统默认的异常处理器
Thread.setDefaultUncaughtExceptionHandler(this);
//获取Context,方便内部使用
mContext = context.getApplicationContext();
}
/**
* 导出异常信息到SD卡
*
* @param ex
*/
private void dumpExceptionToSDCard(Throwable ex) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
//创建文件夹
File dir =new File(PATH);
if (!dir.exists()) {
dir.mkdirs();
}
String time = TimeUtils.date2String(new Date());
//以当前时间创建log文件
File file =new File(PATH +FILE_NAME + time +FILE_NAME_SUFFIX);
try {
//输出流操作
PrintWriter pw =new PrintWriter(new BufferedWriter(new FileWriter(file)));
//导出手机信息和异常信息
PackageManager pm =mContext.getPackageManager();
PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
pw.println("发生异常时间:" + time);
pw.println("应用版本:" + pi.versionName);
pw.println("应用版本号:" + pi.versionCode);
pw.println("android版本号:" + Build.VERSION.RELEASE);
pw.println("android版本号API:" + Build.VERSION.SDK_INT);
pw.println("手机制造商:" + Build.MANUFACTURER);
pw.println("手机型号:" + Build.MODEL);
ex.printStackTrace(pw);
//关闭输出流
pw.close();
}catch (Exception e) {
}
}
/**
* 上传异常信息到服务器
*
* @param ex
*/
private void uploadExceptionToServer(Throwable ex) {
// TODO: 添加异常上传服务器
}
}
2、在application对CrashHandler 初始化,在oncreate方法中。
CrashHandler.getInstance().init(this);