【问题标题】:android pause and restart alarm manager in broadcast receiverandroid在广播接收器中暂停并重新启动警报管理器
【发布时间】:2015-06-24 07:11:14
【问题描述】:

我像这样在我的 MainActivity 中创建 AlarmManager

AlarmManager mgr = (AlarmManager) getApplicationContext()
                .getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(getApplicationContext(),
                TransactionService.class);
PendingIntent   pendingIntent=PendingIntent.getService(getApplicationContext(), 0,   notificationIntent, 0);
       mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 2000, pendingIntent);

我想在某些情况下在广播接收器中停止此警报管理器。下面是广播接收器的代码(不管它是什么)。

public class IncomingSms extends BroadcastReceiver {
private Intent notificationIntent;

public void onReceive(Context context, Intent intent) {
}
}
}

那么我怎样才能访问这个警报管理器并将它暂停到我的广播接收器中,我怎样才能重新启动它呢?

【问题讨论】:

  • 也许您可以使用在后台永久运行的服务。您可以使用任何条件停止并重新启动它..
  • 如果我停止广播接收器中的服务,那么警报管理器必须在 2 秒后重新启动它,所以这不是解决方案
  • 因为AlarmManager不是你的财产,而是系统服务,你不能停止它。您只能取消已安排的活动

标签: android broadcastreceiver alarmmanager


【解决方案1】:
public class IncomingSms extends BroadcastReceiver {
    private Intent notificationIntent;

    public void onReceive(Context context, Intent intent) {
         AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         Intent notificationIntent = new Intent(context, TransactionService.class);
         PendingIntent pendingIntent=PendingIntent.getService(getApplicationContext(), 0,   notificationIntent, 0);
         mgr.cancel(pendingIntent)
    }
}

您只需重建您的 PendingIntent 并将其传递给 AlarmManager 的 cancel() 方法。您的 PendingIntent 的识别将通过检查您的 PendingIntent 的 id 以及包含的 Intent 是否满足此处定义的 filterEquals() 要求来完成:http://developer.android.com/reference/android/content/Intent.html#filterEquals%28android.content.Intent%29

更多信息:http://developer.android.com/reference/android/app/AlarmManager.html#cancel%28android.app.PendingIntent%29

如果您想重新启动,您只需再次注册到您的 PendingIntent。

【讨论】:

    【解决方案2】:

    AlarmManager 启动后不能暂停它,而是可以取消警报管理器并在需要时重新启动它。

    如果您知道警报注册时给出的 id,您可以取消警报事件。

    AlarmManager mgr = (AlarmManager) getApplicationContext()
                    .getSystemService(Context.ALARM_SERVICE);
    Intent notificationIntent = new Intent(getApplicationContext(),
                    TransactionService.class);
    PendingIntent   pendingIntent=PendingIntent.getService(getApplicationContext(), 0,   notificationIntent, 0);
    
    alarmManagerstop.cancel(pendingIntent);
    

    【讨论】:

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