gpt4 book ai didi

android - 如何从android进程中获取错误日志以及何时调用get error log方法?

转载 作者:行者123 更新时间:2023-12-03 08:54:37 25 4
gpt4 key购买 nike

我已经在异常可能的地方实现了try catch。
Android OS会抛出其他不同的异常[数据库异常,权限和其他异常]。我想将这些错误日志数据写入文件{仅在我们的应用程序崩溃时}。

我已经有代码将给定的数据写入文件。我只想知道如何从android进程获取错误日志。

如果发生任何崩溃,则该应用实例不可用。而且我不知道在何处调用get错误日志方法。
在此。
请帮我。

最佳答案

在您的应用程序类中,您可以初始化未处理的异常。回调方法将具有可抛出对象。从该对象中,我们可以获取崩溃日志数据,然后将相同的数据写入文件。

应用程序类:

public class MyApplication extends Application {
// uncaught exception handler variable
private UncaughtExceptionHandler defaultUEH;

public MyApplication() {
defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

// setup handler for uncaught exception
Thread.setDefaultUncaughtExceptionHandler(_unCaughtExceptionHandler);
}

// handler listener
private Thread.UncaughtExceptionHandler _unCaughtExceptionHandler = new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable ex) {
//To write the crash log data to file
AppUtil.getInstance().writeActivityLogToFile(true,
getErrorMessgae(ex));

// re-throw critical exception further to the os (important) to handle
defaultUEH.uncaughtException(thread, ex);
// System.exit(2);
}
};

/**
* To get the crash log message from throwable object
*
* @param e
* - throwable exception object
* @return - the crash log
*/
private String getErrorMessgae(Throwable e) {
StackTraceElement[] stackTrackElementArray = e.getStackTrace();
String crashLog = e.toString() + "\n\n";
crashLog += "--------- Stack trace ---------\n\n";
for (int i = 0; i < stackTrackElementArray.length; i++) {
crashLog += " " + stackTrackElementArray[i].toString() + "\n";
}
crashLog += "-------------------------------\n\n";

// If the exception was thrown in a background thread inside
// AsyncTask, then the actual exception can be found with getCause
crashLog += "--------- Cause ---------\n\n";
Throwable cause = e.getCause();
if (cause != null) {
crashLog += cause.toString() + "\n\n";
stackTrackElementArray = cause.getStackTrace();
for (int i = 0; i < stackTrackElementArray.length; i++) {
crashLog += " " + stackTrackElementArray[i].toString()
+ "\n";
}
}
crashLog += "-------------------------------\n\n";
return crashLog;
}
}

在 list 中的以下标记中声明您的应用程序类:
<application
android:name=".application.FleetLOCApplication"
......>

关于android - 如何从android进程中获取错误日志以及何时调用get error log方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30555877/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com