Reputation: 1528
I have a service which uses PendinIntent
and AlarmManager
to launch another activity after a fixed period of time.
Here is the relevant code of the service:
Calendar cal = Calendar.getInstance(); //Create a calendar
cal.add(Calendar.MINUTE, 1); //Add the set minutes to the alarm
Intent dialogIntent = new Intent(this, alarmRingLayout.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 1234, dialogIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
When the service starts, I also set up a notification which has the a button that can cancel the service incase the user does not want the activity to launch.
On click of the "cancel" button, stopService()
is called:
stopService(new Intent(StopPowerNapAlarmService.this, PowerNapAlarmService.class));
onDestroy()
has the following code which cancels the notification and calls stopSelf()
It also tries to cancel the PendingIntent
and AlarmManager
.
The problem is that the Activity opens up even after after onDestroy
is called. I believe the PendingIntent
and/or AlarmManager
are not getting canceled.
Here is the code for onDestroy()
:
@Override
public void onDestroy() {
Toast.makeText(this, "Alarm Finished", Toast.LENGTH_SHORT).show();
CancelNotification(this, 0);
//Cancel the pending intent and AlarmManager
Intent myntent = new Intent(PowerNapAlarmService.this, PowerNapAlarmService.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,
1234, myntent, PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntent.cancel();
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
am.cancel(pendingIntent);
stopSelf();
}
What is going wrong over here?
Upvotes: 0
Views: 455
Reputation: 1007624
What is going wrong over here?
Your Intent
objects are different, so your PendingIntent
objects are different. This, in turn, means that you are working with different alarms. The first Intent
points to an alarmRingLayout.class
activity. The second Intent
points to a BroadcastReceiver
oddly named PowerNapAlarmService
.
If you want to cancel()
the alarmRingLayout
alarm, create an activity PendingIntent
for alarmRingLayout
, and use that with cancel()
.
Also, please get rid of stopSelf()
in onDestroy()
, as that is not needed and could conceivably cause problems.
Upvotes: 2