Search code examples
androiddateandroid-intentalarmmanager

Date change detection on application start up - Android


I am new to Android programming and face a challenge that probably can be solved in seconds on this forum.

I am trying to figure out how to enable an application during start up to detect whether the date has changed since it's last boot.

When the date has changed, I intend to change the value in the textview. However if it hasn't, the textview wont change. - I know how to create this function however stuck on the date change problem?

I have read on alarmmanager however not sure this is required as it doesn't need to happen at the specific time only during boot up.

Any advise would be appreciated.

Thanks,

p.s I am creating a basic quote application and want to include a quote of the day page. In order to do this, I need to know whether the date has changed in order for the application to change the quote


Solution

  • What you will need is this:
    A SharedPreference with a long value describing the last date.
    A Calendar.

    When your Activity starts (in the onCreate() Method seems like a good place for this) you can get a new Calendar. It will have the current date, and you can extract the day:

    Calendar c = Calendar.getInstance();
    int thisDay = c.get(Calendar.DAY_OF_YEAR); //You can chose something else to compare too, such as DATE..
    long todayMillis = c.getTimeInMillis(); //We might need this a bit later.
    

    You then read the possibly saved value from last time and set the calendar to this value, then compare this with today:

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    long last = prefs.getLong("date", 0); //If we don't have a saved value, use 0.
    c.setTimeInMillis(last);
    int lastDay = c.get(Calendar.DAY_OF_YEAR);
    
    if( last==0 || lastDay != thisDay ){
        //New day, update TextView and preference:
        SharedPreferences.Editor edit = prefs.edit();
        edit.putLong("date", todayMillis);
        edit.commit();
    }