Detect First Run

半腔热情 提交于 2019-11-29 08:54:02

savedInstanceState is more for switching between states, like pausing/resuming, that kind of thing. It must always be created by you, also.

What you want in this case is SharedPreferences.

Something like this:

public static final String PREFS_NAME = "MyPrefsFile"; // Name of prefs file; don't change this after it's saved something

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    SharedPreferences settings = 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("activity", "first time");
        setContentView(R.layout.activity_clean_weather);

        SharedPreferences.Editor editor = settings.edit(); // Open the editor for our settings
        editor.putBoolean("firstRun", false); // It is no longer the first run
        editor.commit(); // Save all changed settings
    } else {
        Log.w("activity", "second time");
        setContentView(R.layout.activity_clean_weather);
    }

}

I basically took this code directly from the documentation for Storage Options and applied it to your situation. It's a good concept to learn early.

You may use a self-defined shared preference to archive your goal.

The fact is that savedInstanceState holds persistent data across activities. As such if you restart the app, savedInstanceState will be null across runs. You should either use a Preference or some data base entry to keep track of your first run. I myself use a SharedPreference for this purpose.

savedInstanceState will be null if the app is not already loaded in memory. If you want to detect whether the app has run for the very first time, you have to apply different technique, such as using sharedPrefs / DB to store a property for the first run.

i.e. Check sharedPrefs for property "firstRun"

if exists, then it is not a first run

else it is the first run

set the firstRun property to true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!