android 在广播接收器中暂停并重启警报管理器

android pause and restart alarm manager in broadcast receiver

我像这样在我的 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) {
}
}
}

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

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。

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