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

时间:2015-06-24 07:11:15

标签: android broadcastreceiver alarmmanager

我在我的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 个答案:

答案 0 :(得分:2)

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。

答案 1 :(得分:0)

启动后您无法暂停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);