gpt4 book ai didi

java - 如何知道上次android应用程序是否崩溃

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:54:34 24 4
gpt4 key购买 nike

我有一个 android 应用程序,我想知道在这个应用程序启动时我的应用程序之前是否崩溃过。此崩溃可能是操作系统为节省内存或任何其他原因在应用程序上强制执行的崩溃。它可能不会被 UnhandledExceptionHandler 捕获。到目前为止我处理的内容如下所示,它没有缓存那些与 native 操作系统相关和内存强制的情况

UncaughtExceptionHandler handler = new UncaughtExceptionHandler();
Thread.setDefaultUncaughtExceptionHandler(handler);

编辑:

请不要推荐第 3 方库。

最佳答案

这将通过 SharedPreferences 实现,首先,当您在 MainActivity 中输入您的应用程序时,创建一个名为 boolean 变量>crash 并将其保存到您的 SharedPreferences 中,值为 false,然后在发生崩溃时,只需将此变量的值重新保存为 true 这将自动覆盖之前存储的 crash 值。

保存值:

private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putBoolean("crash", false);
editor.commit();
}

加载保存的值:

private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
boolean crash = sharedPreferences.getBoolean("crash", false);
if(crash){
// then your app crashed the last time
}else{
// then your app worked perfectly the last time
}
}

因此,在您的崩溃处理程序类中,只需将值保存为 true:

附注这必须针对所有未处理的异常运行,无论来自应用程序还是来自操作系统。

public class CrashHandler extends Application{

public static Context context;

public void onCreate(){
super.onCreate();

CrashHandler.context = getApplicationContext();
// Setup handler for uncaught exceptions.
Thread.setDefaultUncaughtExceptionHandler (new Thread.UncaughtExceptionHandler()
{
@Override
public void uncaughtException (Thread thread, Throwable e)
{
handleUncaughtException (thread, e);
}
});

}

public void handleUncaughtException (Thread thread, Throwable e)
{
e.printStackTrace(); // not all Android versions will print the stack trace automatically

SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(context);
Editor editor = sharedPreferences.edit();
editor.putBoolean("crash", true);
editor.commit();

}

}

关于java - 如何知道上次android应用程序是否崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27899705/

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