个人博客
Crash监控的简单实现方案
前言
本文从Java层及Native展开,简单记录Android中的Crash监控方案。
Java层Crash
Java层的crash监控,可以通过实现Thread.UncaughtExceptionHandler
接口,重写uncaughtException
方法来实现,简单示意代码如下:
public class CrashHandler implements Thread.UncaughtExceptionHandler {
private static Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;
private static Context mContext;
private static String mPath;
public static void init(Context context, String path) {
mContext = context.getApplicationContext();
mPath = path;
defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(new CrashHandler());
}
@Override
public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
File dir = new File(mContext.getExternalCacheDir(), mPath);
if (!dir.exists()) {
dir.mkdirs();
}
long l = System.currentTimeMillis();
File file = new File(dir, l + ".txt");
try {
PrintWriter pw = new PrintWriter(new FileWriter(file));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
pw.println("time: " + sdf.format(new Date()));
pw.println("thread: " + thread.getName());
throwable.printStackTrace(pw