我使用Alarm来从服务器获取数据。 我想给用户提供启动和停止Alarm的选项。 这意味着我必须检查并确定Alarm是否已经设置。 我找到了一些代码,可以告诉我Alarm是否已经设置:
Intent I = new Intent(getApplicationContext(),AlarmReceiver.class);
PendingIntent P = PendingIntent.getBroadcast(getApplicationContext(), 0, I, PendingIntent.FLAG_NO_CREATE);
found = (P!=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 被清除?