Detect First Run

后端 未结 4 692
我在风中等你
我在风中等你 2020-12-18 16:31

I am trying to detect if my app has been run before, by using this code:

(This is in my default Android activity)

@Override
public void onCreate(Bund         


        
4条回答
  •  佛祖请我去吃肉
    2020-12-18 17:18

    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.

提交回复
热议问题