Android的AlarmManager问题设置和放大器;重置警报放大器、警报、问题、Android

2023-09-12 07:44:46 作者:Sparkling crystal 亮晶晶

我用警报从服务器获取数据。 我喜欢给用户来启动和停止警报的选项。 这意味着我要检查,看看闹钟已经设置。 我发现了一些code,告诉我,如果报警已经设为:

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)

问题是这样的工作只有一次。第一次上code,检查现有的报警 将返回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.

这里是code设置报警

here is the code to set 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.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 60000, P); 

和这里是code取消报警:

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 不要使用 PendingIntent FLAG_CANCEL_CURRENT 。 相反,取消 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();