您好,我正在尝试检测我的应用程序是否是第一次打开。如果有,我需要运行一个 Activity ,一旦第二次打开它就不应该再次显示。
这是我的代码:
fragment :
@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();
}
但它所做的只是启动 Activity ,当我再次启动它时,它卡住在白屏中,但检查它显示的日志,就像 else 语句不断地一遍又一遍地运行一样。我对 Android 相当陌生,因此我们将不胜感激一些帮助或建议
最佳答案
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences pref = YourActivityName.this.getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor editor= pref.edit();
boolean firstRun = pref.getBoolean("firstRun", true);
if(firstRun)
{
Log.i("onCreate: ","first time" );
editor.putBoolean("firstRun",false);
editor.commit();
Intent intent = new Intent(getActivity(), TutorialFeaturedActivity.class);
startActivity(intent);
}
else
{
Log.i("onCreate: ","second time");
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
// getSpecials();
}
关于java - Android 使用共享首选项来检查首次运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44131469/