设置&的Android AlarmManager问题重置闹钟 [英] Android AlarmManager problem with setting & resetting an alarm
问题描述
我使用警报从服务器获取数据.我喜欢为用户提供启动和停止警报的选项.这意味着我必须检查警报是否已经设置.我找到了一些代码,告诉我闹钟是否已经设置:
I use an Alarm to fetch data from server. I like to give user the option to start and stop the alarm. This means I have to check and see if alarm is already set. I found some code that tells me if the alarm is already set:
Intent I = new Intent(getApplicationContext(),AlarmReceiver.class);
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_NO_CREATE);
found = (P!=null);
如果闹钟已经设置我取消它但如果它没有设置那么我设置它(就像一个切换)
if the Alarm is already set I cancel it but if it is not set then I set it (like a toggle)
问题是这只能工作一次.第一次用上面的代码检查现有的报警将返回 null 表示没有警报,但在我取消警报后,一旦它返回一个指针但警报没有运行.
Problem is this works only once. The first time the above code to check existing alarms will return null indicating no alarm but after I cancel the alarm once it returns a pointer to something but alarm is not running.
这里是设置闹钟的代码
am = (AlarmManager) getSystemService(getApplicationContext().ALARM_SERVICE);
Intent I = new Intent(getApplicationContext(),AlarmReceiver.class);
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000, P);
这里是取消闹钟的代码:
and here is the code to cancel an alarm:
am = (AlarmManager) getSystemService(getApplicationContext().ALARM_SERVICE);
Intent I = new Intent(getApplicationContext(),AlarmReceiver.class);
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_CANCEL_CURRENT);
am.cancel(P);
我是不是要在取消警报后重置某些内容以使其 PendingIntent 消失.
Am I to reset something after canceling an alarm to make it's PendingIntent go away.
推荐答案
取消 AlarmManager
时,不要使用带有 FLAG_CANCEL_CURRENT标志的
PendingIntent
代码>.相反,在取消警报后明确取消PendingIntent
:
When canceling the AlarmManager
do not use a PendingIntent
with a flag of FLAG_CANCEL_CURRENT
.
Instead, cancel the PendingIntent
explicitly after canceling the alarm:
am = (AlarmManager) getSystemService(getApplicationContext().ALARM_SERVICE);
Intent i = new Intent(getApplicationContext(),AlarmReceiver.class);
PendingIntent p = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);
am.cancel(p);
p.cancel();
这篇关于设置&的Android AlarmManager问题重置闹钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!