Determine if Android app is being used for the first time

前端 未结 16 1252
攒了一身酷
攒了一身酷 2020-11-22 12:47

I am currently developing an android app. I need to do something when the app is launched for the first time, i.e. the code only runs on the first time the program is launch

16条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 13:37

    You can use the SharedPreferences to identify if it is the "First time" the app is launched. Just use a Boolean variable ("my_first_time") and change its value to false when your task for "first time" is over.

    This is my code to catch the first time you open the app:

    final String PREFS_NAME = "MyPrefsFile";
    
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    
    if (settings.getBoolean("my_first_time", true)) {
        //the app is being launched for first time, do something        
        Log.d("Comments", "First time");
    
                 // first time task
    
        // record the fact that the app has been started at least once
        settings.edit().putBoolean("my_first_time", false).commit(); 
    }
    

提交回复
热议问题