Search code examples
javaandroidcookiesnotificationsalarmmanager

Alarm Manager Notification Setting Cookies


I am having some problem when trying to prompt notification based on the timing set by Alarm Manager in Android.

So what I am trying to do is a budget setting application. If the monthly expenses exceed the budget, it will prompt notification. In order to keep the question short, I will just post the part where I interact with Alarm Manager:

AlarmManager mgr = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent notificationIntent = new Intent(context, BudgetAlarm.class);
        PendingIntent pi = null;
        if (bm.getReminderNotify().equals("Y")
                && percentage >= 90) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 1);
            notificationCount = notificationCount + 1;

            // Set request flag to 1 so that the same pending intent in broadcastReceiver
            notificationIntent.putExtra("NotifyCount", notificationCount);
            pi = PendingIntent.getBroadcast(context, 1,
                    notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);

What I am trying to do here is to check if the expenses exceed the budget. And inside the BudgetAlarm class, I am prompting the notification:

private NotificationManager mNotificationManager;
private Notification notification;

@Override
public void onReceive(Context context, Intent intent) {
    mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 1,
            new Intent(), 0);
    notification = new Notification(R.drawable.ic_launcher, "Notification",
            System.currentTimeMillis());
    notification.setLatestEventInfo(context, "Budget Reminder",
            "Your monthly expenses nearly exceed the budget!",
            contentIntent);
    mNotificationManager.notify(
            Integer.parseInt(intent.getExtras().get("NotifyCount")
                    .toString()), notification);
}

My problem now is it does set and trigger the alarm manager every day. But let's say today I did not run the apps, it does prompt me a notification to notify me. But after a while, I launch the app, then it prompt me again.

I wonder is there any way to set the notification to just notify once per day regardless of how many times I launch the apps. I was actually thinking of something like cookies or shared preference.

Thanks in advance.

EDIT

public class BudgetAlarm extends BroadcastReceiver {
private NotificationManager mNotificationManager;
private Notification notification;

@Override
public void onReceive(Context context, Intent intent) {
    saveDay(context);
    if (sameDay(context) == false) {
        mNotificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        PendingIntent contentIntent = PendingIntent.getActivity(context, 1,
                new Intent(), 0);
        notification = new Notification(R.drawable.ic_launcher,
                "Notification", System.currentTimeMillis());
        notification.setLatestEventInfo(context, "Budget Reminder",
                "Your monthly expenses nearly exceed the budget!",
                contentIntent);
        mNotificationManager.notify(
                Integer.parseInt(intent.getExtras().get("NotifyCount")
                        .toString()), notification);
        saveDay(context);
    }
}

private boolean sameDay(Context context) {
    boolean isSameDay = false;
    SharedPreferences pref = context.getSharedPreferences("PrefKey",
            Context.MODE_PRIVATE);

    Calendar cal = Calendar.getInstance();
    SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
    Date today = cal.getTime();
    String day = format.format(today);

    String savedDate = pref.getString("SaveDateKey", "NONE");

    if (savedDate.equals(day)) {
        isSameDay = true;
    } else {
        isSameDay = false;
    }
    return isSameDay;
}

private void saveDay(Context context) {
    SharedPreferences pref = context.getSharedPreferences("PrefKey",
            Context.MODE_PRIVATE);
    Editor editor = pref.edit();
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
    Date today = cal.getTime();
    String day = format.format(today);
    editor.putString("SaveDateKey", day);
    editor.commit();
}

}


Solution

  • I think You are on the right way with shared preferences. This could be a scenario in Your app: make a method to know if the same day is equal, if not, save the date when You start the app:

      private boolean sameDay(){
    
      boolean isSameDay = false;
     SharedPreferences pref = getApplicationContext().getSharedPreferences(YOUR_PREF_KEY, Context.MODE_PRIVAT);
    
     Calendar cal = Calendar.getInstance();
     SimpleDateFormat format =  new SimpleDateFormat("dd.MM.yyyy");
     Date today = cal.getTime();
     String day = format.format(today);
    
     String savedDate = pref.getString(YOUR_SAVED_DATE_KEY,"NONE");
    
     if(savedDate.equals(day){
        isSameDay=true;
     }else{
        isSameDay=false;
      } 
        return isSameDay;
    }
    

    And to save the current day:

    private void saveDay(){
    
      SharedPreferences pref = getApplicationContext().getSharedPreferences(YOUR_PREF_KEY, Context.MODE_PRIVAT);
    
    
     Editor editor = pref.edit();
    
     Calendar cal = Calendar.getInstance();
     SimpleDateFormat format =  new SimpleDateFormat("dd.MM.yyyy");
     Date today = cal.getTime();
     String day = format.format(today);
    
     editor.putString(YOUR_SAVED_DATE_KEY,day);
     editor.commit();
     }
    

    And then You just handling this inside Your onReceive():

     if(sameDay==true){
        //don´t notify
    
     }else{
      //notify and save the day
      saveDay();
     }