【问题标题】:AlarmManager still triggering alarm after canceling the associated service and PendingIntentAlarmManager 在取消关联服务和 PendingIntent 后仍然触发警报
【发布时间】:2014-06-14 20:00:13
【问题描述】:

我有一项服务,它使用PendinIntentAlarmManager 在固定时间后启动另一个活动。

这里是服务的相关代码:

       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() 它还尝试取消PendingIntentAlarmManager

问题是即使在调用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


    【解决方案1】:

    这里出了什么问题?

    您的Intent 对象不同,因此您的PendingIntent 对象也不同。反过来,这意味着您正在使用不同的警报。第一个Intent 指向alarmRingLayout.class 活动。第二个Intent 指向一个奇怪的BroadcastReceiver PowerNapAlarmService

    如果您想cancel()alarmRingLayout 警报,请为alarmRingLayout 创建一个活动PendingIntent,并将其与cancel() 一起使用。

    另外,请去掉 onDestroy() 中的 stopSelf(),因为这不是必需的,并且可能会导致问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多