Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show alert on first launch application of each day in android

I am developing Android app in which i got stuck at one point,

What i want to do is,

When user launches the app for the first time in a day, i want to show him a some alert. And when he opens a app for the second time in same day it will not get an alert. (he will get an alert only for the first launch of app in day).

next day again if he opens the app for the first time again he will get alert and on second time he will not get an alert.

In short: User should get alert on first launch of each day.

Any idea, how should i achieve this ? Thanks in advance.

like image 646
Mr Nice Avatar asked Dec 05 '22 06:12

Mr Nice


2 Answers

We can achieve this via a shared preference. In your first activity, have a method which does the following step by step in oncreatemethod:

1. Read a value (lastlaunchdate) from shared preference.

2. Check if current date = lastlaunchdate

3. If #2 is true, then ignore and proceed with usual flow

4. If #2 is false, then  

 4.a display the alert box

  4.b save current date as lastlaunchdate in shared preference.

Sample code:

if (sharedPref.loadSharedPreference(getApplicationContext(), "LAST_LAUNCH_DATE").equals(new SimpleDateFormat("yyyy/MM/dd", Locale.US).format(new Date())))
{
    // Date matches. User has already Launched the app once today. So do nothing.
}
else
{
    // Display dialog text here......
    // Do all other actions for first time launch in the day...
    // Set the last Launched date to today.
    sharedPref.saveSharedPreference(getApplicationContext(), "LAST_LAUNCH_DATE", new SimpleDateFormat("yyyy/MM/dd", Locale.US).format(new Date()));
}
like image 142
Nishanthi Grashia Avatar answered Dec 10 '22 11:12

Nishanthi Grashia


A more explicit example of Nishanthi's solution that works great for me:

SharedPreferences sharedPref = getSharedPreferences(PREFS_NAME, 0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String currentDate = sdf.format(new Date());
        if (sharedPref.getString("LAST_LAUNCH_DATE","nodate").contains(currentDate)){
            // Date matches. User has already Launched the app once today. So do nothing.
        }
        else
        {
            // Display dialog text here......
            // Do all other actions for first time launch in the day...
            new CheckUpgradeStatus().execute();
            // Set the last Launched date to today.
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString("LAST_LAUNCH_DATE", currentDate);
            editor.commit();
        }
like image 30
Will Evers Avatar answered Dec 10 '22 13:12

Will Evers