public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static final String TAG = "CrashHandler";
private static final boolean DEBUG = true;
//文件路径
private static final String PATH = Environment.getExternalStorageDirectory().getPath() +File.separator+ "crash";
private static final String FILE_NAME = "crash";
private static final String FILE_NAME_SUFEIX = ".trace";
private static Thread.UncaughtExceptionHandler mDefaultCrashHandler;
private static CrashHandler mCrashHandler = new CrashHandler();
private Context mContext;
private CrashHandler() {
}
public static CrashHandler getInstance() {
return mCrashHandler;
}
public void init(Context context) {
mDefaultCrashHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(this);
mContext = context.getApplicationContext();
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
try {
//将文件写入sd卡
writeToSDcard(ex);
//写入后在这里可以进行上传操作
} catch (IOException e) {
e.printStackTrace();
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
ex.printStackTrace();
//如果系统提供了默认异常处理就交给系统进行处理,否则自己进行处理。
if (mDefaultCrashHandler != null) {
mDefaultCrashHandler.uncaughtException(thread, ex);
} else {
Process.killProcess(Process.myPid());
}
}
//将异常写入文件
private void writeToSDcard(Throwable ex) throws IOException, PackageManager.NameNotFoundException {
//如果没有SD卡,直接返回
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
Log.e(TAG, "sdCard unmounted ");
return;
}
File filedir = new File(PATH);
if (!filedir.exists()) {
filedir.mkdirs();
}
long currenttime = System.currentTimeMillis();
String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(currenttime));
File exfile = new File(PATH +File.separator+FILE_NAME+time + FILE_NAME_SUFEIX);
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(exfile)));
Log.e("错误日志文件路径",""+exfile.getAbsolutePath());
pw.println(time);
PackageManager pm = mContext.getPackageManager();
PackageInfo pi = pm.getPackageInfo(mContext.getPackageName(), PackageManager.GET_ACTIVITIES);
//当前版本号
pw.println("App Version:" + pi.versionName + "_" + pi.versionCode);
//当前系统
pw.println("OS version:" + Build.VERSION.RELEASE + "_" + Build.VERSION.SDK_INT);
//制造商
pw.println("Vendor:" + Build.MANUFACTURER);
//手机型号
pw.println("Model:" + Build.MODEL);
//CPU架构
pw.println("CPU ABI:" + Build.CPU_ABI);
ex.printStackTrace(pw);
pw.close();
}
}
调用
public class BaseApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
CrashHandler crashHandler=CrashHandler.getInstance();
crashHandler.init(this);
}
}
当捕捉到异常,会在本地保存一个这些格式的文件: