android - SharedPreference 未按预期工作

标签 android sharedpreferences

我有一个 Activity ,我只想在应用程序第一次运行时运行。我检查了返回 bool 值的指定共享首选项。如果它返回 true 它将被启动,它将被设置为 false,这样下次打开应用程序时它就不会运行。但是我的实现出错了。每次我打开 BeforMain1 Activity 时都会打开。有人可以告诉我我的代码有什么问题吗?

sharedPreferences = getSharedPreferences("ShaPreferences", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor=sharedPreferences.edit();
            boolean  firstTime=sharedPreferences.getBoolean("first", true);
            if(firstTime) {
                editor.putBoolean("first",false);
                Intent intent = new Intent(SplashScreen.this, BeforeMain1.class);
                startActivity(intent);
            }
            else
            {
                Intent intent = new Intent(SplashScreen.this, MainActivity.class);
                startActivity(intent);
            }

最佳答案

您忘记提交 SharedPreferences 更改,

if(firstTime) {
      editor.putBoolean("first",false);
      //For commit the changes, Use either editor.commit(); or  editor.apply();.
      editor.commit();  or  editor.apply();
      Intent intent = new Intent(SplashScreen.this, BeforeMain1.class);
      startActivity(intent);
}else {
      Intent intent = new Intent(SplashScreen.this, MainActivity.class);
      startActivity(intent);
}

关于android - SharedPreference 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33455355/

相关文章:

android - react 导航 : StackNavigator transition for Android

android - 如何使用uiautomator基于同一父对象的其他对象选择特定对象

android - 使用 Android DropBox API 加密 DropBox 文件

java - Android SharedPreferences/PreferenceFragment 不工作

Android SharedPreferences 不保存

android - AlertDialog.Builder setItems 列表与另一个

java - 如何在 Android 中使用 Genderize io Api 获取用户性别

android - 如何在 Handler android 中使用共享首选项

android - 如何通过 SharedPreferences 保存解析的推送通知

Android Studio - Android Device Monitor 的文件资源管理器不工作