In my app, I created a SharedPreference which is set to false when I have clicked on a button.

This is for making a first Setup activity which is only shown when the app has not been started for the Moment.

This is the code for Setting that it wasn't the first start:

getSharedPreferences(KEY, Context.MODE_PRIVATE).edit().putBoolean(KEY_IS_FIRST_TIME, false).commit();

This is the first time start checker:

public boolean isFirstTime(){
    return getSharedPreferences(KEY, Context.MODE_PRIVATE).getBoolean(KEY_IS_FIRST_TIME, true);
}

How must the code in the onCreate of MainActivity be that SetupActivity.class is started when KEY_IS_FIRST_TIME is true?

Thanks

有帮助吗?

解决方案

All you need to do is check if the value for the first time key is set to true, and then launch the Activity, as well as set the value to false for future launches:

SharedPreferences prefs = getSharedPreferences(KEY, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
boolean isFirst = prefs.getBoolean(KEY_IS_FIRST_TIME, true);
if(isFirst) {
    Intent intent = new Intent(this, SetupActivity.class);
    editor.putBoolean(KEY_IS_FIRST_TIME, false);
    editor.commit();
    startActivity(intent);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top