gpt4 book ai didi

android - SharedPreferences 在 Android 中无法正常工作

转载 作者:搜寻专家 更新时间:2023-11-01 08:43:06 24 4
gpt4 key购买 nike

我的应用程序中有一个帮助 Activity ,我希望它仅在首次运行时启动。

我试过这个:

在创建帮助 Activity 时:

SharedPreferences settings = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", true);
editor.commit();

Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);

在帮助 Activity 的onResume中:

@Override
public void onResume() {
super.onResume();
SharedPreferences settings = getSharedPreferences("prefs", 0);
boolean firstRun = settings.getBoolean("firstRun", true);
if (!firstRun) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
Log.d("TAG1", "firstRun(false): " + Boolean.valueOf(firstRun).toString());
} else {
Log.d("TAG1", "firstRun(true): " + Boolean.valueOf(firstRun).toString());
}
}

在MainActivity的onCreate中:

SharedPreferences settings = getSharedPreferences("prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("firstRun", false);
editor.commit();

boolean firstRun = settings.getBoolean("firstRun", true);
Log.d("TAG1", "firstRun: " + Boolean.valueOf(firstRun).toString());

但是它不显示帮助 Activity ,当它运行应用程序时它只是跳转到 MainActivity!!

我的应用程序中有一个退出按钮,当我想使用该按钮退出应用程序时,它只会再次显示 MainActivity 并且不会退出应用程序。

最佳答案

MainActivity 的 onCreate 中执行此操作。如果您将 MainActivity 设置为启动器 Activity ,那么这就是您所需要的。这是我会推荐的。

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

boolean firstRun = settings.getBoolean("firstRun", true);
if (firstRun) {
settings.edit().putBoolean("firstRun", false).apply();
//start help activity
}

使用 MainActivity 作为启动器 Activity,您应该可以更快地启动,因为您不会每次都创建两个 Activity。并且您可以避免在后台堆栈中有两个 Activity 。

ps:Google 不建议使用“退出”按钮。相反,您应该依靠后退\主页按钮关闭应用程序,并让操作系统决定何时销毁应用程序。
Is quitting an application frowned upon?

关于android - SharedPreferences 在 Android 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30957047/

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