Search code examples
androiddatesharedpreferencesalarmmanager

registering first date the app is launched


I am developing an android app and I need to do something every month since the app is launched for the first time it is launched, the app will notify the user. how should i keep only the first date?

i used

  Calendar calendar = Calendar.getInstance();
    final int day = calendar.get(Calendar.DAY_OF_MONTH);
    final int month = calendar.get(Calendar.MONTH);
    Toast.makeText(getApplicationContext(), day + "\n" + month,
            Toast.LENGTH_LONG).show();

but it changes every time i run the app.

any better ideas?

Thanks


Solution

  • You can use the SharedPreferences. It will not allow you to store an Date object directly, but you can store a long which you can use for saving the date.getTime() value which represents the milliseconds since January 1, 1970, 00:00:00 GMT.

    This is an example Activity that demonstrates this.

    public class MyDateActivity extends Activity {
        public static final String PREFS_NAME = "MyPrefsFile";
        public static final String PREFS_LONG_DATE_FIRST_RUN = "FirstRun";
    
        private Date firstRunDate;
    
        @Override
        protected void onCreate(Bundle state){
            super.onCreate(state);
    
            // Restore preferences
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            if (settings.contains(PREFS_LONG_DATE_FIRST_RUN)) {
                // Found date in settings
                long dateFirstRun = settings.getLong(PREFS_LONG_DATE_FIRST_RUN, 0);
                firstRunDate = new Date(dateFirstRun);
            } else {
                // First time running
                firstRunDate = new Date();
            }
        }
    
        @Override
        protected void onStop(){
            super.onStop();
    
            // Get preferences
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    
            // Only write the first run date if settings don't contain a first run date.
            if (!settings.contains(PREFS_LONG_DATE_FIRST_RUN)) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putLong(PREFS_LONG_DATE_FIRST_RUN, new Date().getTime());
                editor.apply();
            }
        }
    }