Android实现APP奔溃日志记录保存

public class CrashHandler implements java.lang.Thread.UncaughtExceptionHandler {
    private java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler;

    public void init() {
        defaultUncaughtExceptionHandler = java.lang.Thread.getDefaultUncaughtExceptionHandler();
        java.lang.Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        java.lang.String externalStorageDirectoryPath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
        java.text.DateFormat dateFormatForDate = new java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.getDefault());
        java.util.Date date = new java.util.Date();
        java.lang.String path = externalStorageDirectoryPath  + java.io.File.separator + "crash-" + dateFormatForDate.format(date) + ".log";
        java.lang.StringBuilder stringBuilder = new java.lang.StringBuilder();
        java.text.DateFormat dateFormatForDateTime = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss", java.util.Locale.getDefault());
        java.lang.String currentTime = dateFormatForDateTime.format(date);
        stringBuilder.append("CrashTime:").append(currentTime).append("\r\n");
        java.io.StringWriter stringWriter = new java.io.StringWriter();
        java.io.PrintWriter printWriter = new java.io.PrintWriter(stringWriter);
        e.printStackTrace(printWriter);
        java.lang.String stackTrace = stringWriter.toString();
        stringBuilder.append(stackTrace);
        try {
            java.io.File logFile = new java.io.File(path);
            java.io.FileWriter fileWriter = new java.io.FileWriter(logFile, true);
            fileWriter.write(stringBuilder.toString());
            fileWriter.close();
        } catch (java.io.IOException ioException) {
            ioException.printStackTrace();
        }
        if (defaultUncaughtExceptionHandler != null) {
            defaultUncaughtExceptionHandler.uncaughtException(t, e);
        } else {
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }
}

然后在自定义Application类的onCreate方法初始化即可

@Override
public void onCreate() {
    super.onCreate();
    CrashHandler crashHandler = new CrashHandler();
    crashHandler.init();

}

你可能感兴趣的:(android,python,开发语言)