【问题标题】:Android AlarmManager problem with setting & resetting an alarmAndroid AlarmManager 设置和重置闹钟的问题
【发布时间】:2011-02-10 22:01:57
【问题描述】:

我使用警报从服务器获取数据。 我喜欢让用户选择启动和停止警报。 这意味着我必须检查是否已经设置了警报。 我找到了一些代码告诉我是否已经设置了闹钟:

Intent I = new Intent(getApplicationContext(),AlarmReceiver.class);
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_NO_CREATE);
found = (P!=null);

如果警报已经设置,我取消它,但如果它没有设置,那么我设置它(就像一个切换)

问题是这只能工作一次。第一次用上面的代码检查已有的告警 将返回 null 表示没有警报,但在我取消警报后,一旦它返回一个指针 到某事,但警报没有运行。

这里是设置闹钟的代码

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); 

这是取消警报的代码:

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 消失。

【问题讨论】:

  • 我不太确定您为什么要执行检查以查看警报是否已存在。你能解释一下你的理由吗?
  • 我想要一个按钮来作为开关。如果我的闹钟设置因应用程序崩溃而丢失,也可以使用该按钮作为指示器。当用户单击小部件时,我使用警报更新小部件,它会打开一个活动,用户可以在其中查看是否设置了警报。我害怕的是我设置闹钟后它会被关闭,用户不会知道它已经关闭了。

标签: android android-intent alarm alarmmanager android-pendingintent


【解决方案1】:

取消AlarmManager 时,不要使用带有FLAG_CANCEL_CURRENT 标志的PendingIntent。 相反,取消警报后显式取消PendingIntent

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();

【讨论】:

  • 这应该收到+50,因为没有其他帖子地址取消PendingIntent以及AlarmManager,我正在使用(PendingIntent.getBroadcast(getBaseContext(), 0, checkIntent, PendingIntent.FLAG_NO_CREATE) != null);检查我的警报是否正在运行,这是在不重新启动我的活动的情况下唯一有效的方法。干得好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-09-17
  • 1970-01-01
  • 1970-01-01
  • 2012-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多