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);
}
}
}
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():
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