tags:

views:

162

answers:

1

Hi, I'm writing something like a reminder for users. Users will set reminders for their events, when the time comes, a repeating alarm will be set to trigger a status bar notification. But the alarm seems non-stop after I selected the notification or cleared the notification. I am not sure where to cancel this repeating alarm. Below are some of the codes: Set up the repeating alarm in my main activity

alarmTime = Calendar.getInstance();
Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this,
               0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmTime.add(Calendar.MINUTE,offset_time);

//Schedule the alarm
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(),30*1000,sender);

In my OnReceive method, I just display the notification in status bar and set the flag as FLAG_AUTO_CANCEL

    manager = (NotificationManager) context
            .getSystemService(context.NOTIFICATION_SERVICE);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.medical, text,
            System.currentTimeMillis());

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, i,
            0);

    notification.flags = Notification.FLAG_AUTO_CANCEL;

    manager.notify(R.string.service_text, notification);

How can I stop the alarm when the user selects the notification or clears it?

A: 

Call cancel() on AlarmManager with an equivalent PendingIntent to the one you used with setRepeating():

Intent intent = new Intent(this, AlarmReceive.class);
PendingIntent sender = PendingIntent.getBroadcast(this,
               0, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

alarmManager.cancel(sender);
CommonsWare
I want to cancel this alarm after user sees the notification, but the notification is defined in onReceive. So how can I determine whether user knows about the notification in my main activity before I cancel the alarm?Thanks
Wen
@Wen: use a different Intent (e.g., different action) to start your main activity from the Notification than you use for the launcher. Or, if you are bringing an existing instance of the main activity to the foreground, your Notification will trigger onNewIntent() in the activity, so you can cancel the alarm there.
CommonsWare
The notification will trigger another activity. What do u mean by use a diff Intent to start activity from the Notification than use for launcher?
Wen
@Wen: "The notification will trigger another activity.". OK, put your cancel-the-alarm code in `onCreate()` of that activity, then.
CommonsWare
Thanks Mark, it solves the problem.
Wen