我正在研究如何取消闹钟,我遇到了这两种方法。应该在什么情况下使用哪一个,为什么?它们是一样的吗?
我目前正在这样做:
Intent alarmIntent = new Intent(ChangeAlarmActivity.this, AlarmReceiver.class);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(ChangeAlarmActivity.this, (int)alarm.getID(),
alarmIntent, 0);
pendingAlarmIntent.cancel();
这与下面的有何不同?
Intent alarmIntent = new Intent(ChangeAlarmActivity.this, AlarmReceiver.class);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(ChangeAlarmActivity.this, (int)alarm.getID(),
alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pendingAlarmIntent);
最佳答案
Are they both the same?
没有。
如果你想取消一个闹钟,在AlarmManager
上调用cancel()
。
PendingIntent
上的 cancel()
可能看起来具有相同的效果——无论您的警报事件应该触发什么,都不再发生。但是,您随后假设 AlarmManager
会检测到这一点并在其端进行清理,但这是无法保证的。特别是对于 _WAKEUP
警报,这可能会导致设备无缘无故地被唤醒,从而浪费电池生命周期。
Which one should be used in what situation and why?
我确信 PendingIntent
上的 cancel()
有用例。我不能说出任何具体的名字,因为我从未见过它被使用过。通常,当您使用 PendingIntent
时,任何“取消”语义都在 PendingIntent
的使用上(例如,您 cancel( )
通过 AlarmManager
发出警报,您通过 NotificationManager
cancel()
通知),而不是在 PendingIntent
本身。
PendingIntent
上的 cancel()
的一个地方,因此,将是您传递 PendingIntent
并且没有“cancel"来还原它,或者您明确希望使用 cancel()
作为还原机制。例如,如果您正在创建某种插件机制,并且插件向主机应用程序发送了一个 PendingIntent
,插件可能会使用 cancel()
来表示“停止使用PendingIntent
”,主机应用程序会在下次尝试 send()
PendingIntent
时发现它并得到异常。就我个人而言,我不是这个的忠实拥护者——很多情况下,AlarmManager
行,如果主机应用程序无法正确处理这种情况,您不知道它可能使用哪些资源。但是,如果使用得当,它肯定会起作用。
How is that different to this below?
“下面”是我建议您使用的。
关于android - pendingAlarmIntent.cancel() 或 AlarmManager.cancel(pendingAlarmIntent)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16202651/