我使用警报从服务器获取数据。我喜欢让用户选择启动和停止警报。这意味着我必须检查是否已经设置了警报。我发现一些代码告诉我是否已经设置了闹钟:
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 消失。