【发布时间】:2014-06-14 20:00:13
【问题描述】:
我有一项服务,它使用PendinIntent 和AlarmManager 在固定时间后启动另一个活动。
这里是服务的相关代码:
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);
当服务启动时,我还设置了一个通知,其中有一个按钮,可以取消服务,以防用户不希望启动活动。
点击“取消”按钮,stopService() 被调用:
stopService(new Intent(StopPowerNapAlarmService.this, PowerNapAlarmService.class));
onDestroy() 有以下代码取消通知并调用stopSelf()
它还尝试取消PendingIntent和AlarmManager。
问题是即使在调用onDestroy 之后,Activity 也会打开。我相信PendingIntent 和/或AlarmManager 不会被取消。
这是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();
}
这里出了什么问题?
【问题讨论】:
标签: android android-service android-pendingintent android-alarms