Determine if Android app is being used for the first time

前端 未结 16 1137
攒了一身酷
攒了一身酷 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:20

    If you are looking for a simple way, here it is.

    Create a utility class like this,

    public class ApplicationUtils {
    
      /**
      * Sets the boolean preference value
      *
      * @param context the current context
      * @param key     the preference key
      * @param value   the value to be set
      */
     public static void setBooleanPreferenceValue(Context context, String key, boolean value) {
         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
         sp.edit().putBoolean(key, value).apply();
     }
    
     /**
      * Get the boolean preference value from the SharedPreference
      *
      * @param context the current context
      * @param key     the preference key
      * @return the the preference value
      */
     public static boolean getBooleanPreferenceValue(Context context, String key) {
         SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
         return sp.getBoolean(key, false);
     }
    
    }
    

    At your Main Activity, onCreate()

    if(!ApplicationUtils.getBooleanPreferenceValue(this,"isFirstTimeExecution")){
    Log.d(TAG, "First time Execution");
    ApplicationUtils.setBooleanPreferenceValue(this,"isFirstTimeExecution",true);
    // do your first time execution stuff here,
    }
    

提交回复
热议问题