0

I have an application which uses AlarmManager to schedule Notifications if there is any event coming up. This works well.

The problem is that every time the user instantiates the application, it displays the StatusBar Notification if it is the Event day. I would like to show the StatusBar Notification only when the app is not active (ie. closed).

@Override
public void onCreate(Bundle savedInstanceState)
{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simple_calendar_view);

        if (notification_value == true) {
            int dayOfEvent = day;
            if (notification_day == 1) {
                dayOfEvent = day + 1;

            }
            if(isHoliday(dayOfEvent, month, year))
            {
                String mn = monthName[month-1];
                String date_string = setParameter(year, mn, dayOfEvent);
                startAlarm(year, (month-1), day, hour, mins, date_string);
            }
        }
} 
input
  • 7,503
  • 25
  • 93
  • 150

1 Answers1

0

To prevent AlarmManager from creating Notifications while your app is running simply use AlarmManager.cancel(PendingIntent intent) in onResume() and recreate your alarms in onPause().

From the Android Documentation on AlarmManager.cancel():

Remove any alarms with a matching Intent. Any alarm, of any type, whose Intent matches this one (as defined by filterEquals(Intent)), will be canceled.

This states that you don't have to keep an references to your old alarms, any alarm with a matching Intent will be cancelled.

Lastly, I don't recommend moving the code to onCreate() and onDestory because the app can be paused by the user (with the Home Button for instance) and later killed by the OS. In this case the onDestroy() method is never called. If having Notifications appear while the app is in the background is unacceptable please read this detailed answer on how to track when your app is actually killed: Checking if an Android application is running in the background

Community
  • 1
  • 1
Sam
  • 86,580
  • 20
  • 181
  • 179
  • Okay, Sam, I did as you suggested. Cancelled the alarms on onResume() and recreated them onPause(). The problem I faced with this is that since the notifications are being instantiated on onCreate(), it first runs the notifications and perhaps then cancels the alarms on onResume() which defeats the purpose. I'm not sure how else to do this? – input Aug 13 '12 at 05:46
  • You should only create your alarms in onPause(), not onCreate(). As you said there is no purpose in launching a notification in onCreate() only to cancel them in onResume(). – Sam Aug 13 '12 at 05:55