【发布时间】:2017-10-23 05:01:40
【问题描述】:
您好,我正在尝试检测我的应用是否已首次打开。如果有,我需要运行一个活动,一旦它第二次打开,它就不应该再次显示它。
这是我的代码:
片段:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
//startActivity(intent);
SharedPreferences settings = this.getActivity().getSharedPreferences(PREFS_NAME, 0); // Get preferences file (0 = no option flags set)
boolean firstRun = settings.getBoolean("firstRun", true); // Is it first run? If not specified, use "true"
if(firstRun) {
Log.w("onCreate: ","first time" );
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
editor.putBoolean("firstRun", false); // It is no longer the first run
editor.apply(); // Save all changed settings
} else {
Log.w("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
getSpecials();
}
但它所做的只是启动活动,当我再次启动它时,它会冻结在一个白屏中,但检查它显示的日志,就像 else 语句不断地反复运行一样。我对 Android 还很陌生,因此非常感谢您提供一些帮助或建议
【问题讨论】:
-
你应该使用 editor.commit();用于保存更改
-
请问
getActivity().finish()有什么用?这就是我看到的第一次和第二次运行之间的区别。这可能会让你回到你检查第一次运行并进入无限循环的类?! -
当我使用 editor.commit();或应用我仍然得到相同的结果,ide 也告诉我我应该使用 apply 而不是 commit 但同样的问题。
-
@Nico 我使用 getActivity().finish();要结束正在运行的教程活动,我忘了在问题中将其取出,因为它仍然无法解决任何问题
-
请将所有代码发布到这个文件中。
标签: java android android-fragments android-intent android-sharedpreferences