import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.text.SimpleDateFormat;
import java.util.Date;
public class CrashHandler implements UncaughtExceptionHandler {
private static final String TAG = "CrashHandler";
private static final String CRASH_DIR = "crashes";
private static final String CRASH_LOG_PATH = "crash_log.txt";
private Thread.UncaughtExceptionHandler defaultUEH;
private Context context;
private CrashHandler() {
this.defaultUEH = Thread.getDefaultUncaughtExceptionHandler();
}
private static CrashHandler instance;
public static CrashHandler getInstance() {
if (instance == null) {
instance = new CrashHandler();
}
return instance;
}
public void init(Context context) {
this.context = context;
Thread.setDefaultUncaughtExceptionHandler(this);
}
@Override
public void uncaughtException(Thread t, Throwable e) {
if (e == null) {
if (defaultUEH != null) {
defaultUEH.uncaughtException(t, e);
}
return;
}
// 收集异常信息
String exceptionInfo = collectExceptionInfo(e);
String deviceInfo = collectDeviceInfo();
saveCrashInfoToFile(deviceInfo, exceptionInfo);
// 如果系统提供了默认的未捕获异常处理,则交给系统去处理
if (defaultUEH != null) {
defaultUEH.uncaughtException(t, e);
}
}
private String collectDeviceInfo() {
StringBuilder deviceInfo = new StringBuilder();
// 可以添加更多设备信息
deviceInfo.append("Brand: ").append(Build.BRAND).append("\n");
deviceInfo.append("Model: ").append(Build.MODEL).append("\n");
deviceInfo.append("Android Version: ").append(Build.VERSION.RELEASE).append("\n");
return deviceInfo.toString();
}
private String collectExceptionInfo(Throwable e) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
Throwable cause = e.getCause();
while (cause != null) {
cause.printStackTrace(printWriter);
cause = cause.getCause();
}
printWriter.close();
String exceptionInfo = writer.toString();
Log.e("xxx",exceptionInfo);
return exceptionInfo;
}
private void saveCrashInfoToFile(String deviceInfo, String exceptionInfo) {
File dir = context.getExternalFilesDir(CRASH_DIR);
if (!dir.exists()) {
dir.mkdirs();
}
File file = new File(dir, CRASH_LOG_PATH);
try {
PrintWriter printWriter = new PrintWriter(file);
printWriter.println(deviceInfo);
printWriter.println(exceptionInfo);
printWriter.close();
} catch (Exception e) {
Log.e(TAG, "An error occurred while writing crash info to file");
}
}
}
import android.app.Application
class MyApplication : Application() {
override fun onCreate() {
super.onCreate()
CrashHandler.getInstance().init(this)
}
}
保存的目录:
手机根目录->Android->data->com.xx.xx->files->crashes->crash_log.txt