在阅读了大量示例代码之后,我试图找出实现以下目标的最简单方法:
我希望能够安排一个回调到我的Alarm BroadcastReceiver的Intent,然后启动我的服务。但是,我想设置它以便每天调用两次Intent,并且只安排警报(如果它们尚未设置)(同样用于取消警报)。
但是,我不确定以下代码是否是设置和取消警报的正确方法。
//Static function for setting the alarm
//My midday calendar object (cal1)
...
//My evening calendar object (cal2)
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE)
Intent myIntent = new Intent(context, MyAlarmReceiver.class);
PendingIntent firstCallIntent = PendingIntent.getBroadcast(context, FIRST_CALL_ID, myIntent, PendingIntent.FLAG_NO_CREATE);
PendingIntent secondCallIntent= PendingIntent.getBroadcast(context, SECOND_CALL_ID, myIntent, PendingIntent.FLAG_NO_CREATE);
if(firstCallIntent == null){
if(DEBUG){
Log.d(TAG, "Setting Midday Alarm");
}
firstCallIntent = PendingIntent.getBroadcast(context, FIRST_CALL_ID, myIntent, 0);
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal1.getTimeInMillis(), AlarmManager.INTERVAL_DAY, firstCallIntent);
}
if(secondCallIntent == null){
if(DEBUG){
Log.d(TAG, "Setting Evening Alarm");
}
secondCallIntent = PendingIntent.getBroadcast(context, SECOND_CALL_ID, myIntent, 0);
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal2.getTimeInMillis(), AlarmManager.INTERVAL_DAY, secondCallIntent);
}
//Static call to cancel the alarm.
AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE)
Intent myIntent = new Intent(context, MyAlarmReceiver.class);
PendingIntent firstCallIntent = PendingIntent.getBroadcast(context, FIRST_CALL_ID, myIntent, 0);
alarms.cancel(firstCallIntent);
firstCallIntent.cancel();
PendingIntent secondCallIntent = PendingIntent.getBroadcast(context, SECOND_CALL_ID, myIntent, 0);
alarms.cancel(secondCallIntent);
secondCallIntent.cancel();
答案 0 :(得分:1)
这对我来说似乎没问题,但是您可以将间隔设置为
,而不是创建两个日历对象AlarmManager.INTERVAL_DAY/2
除非你的意图做不同的事情。
此外,
alarms.cancel(firstCallIntent);
alarms.cancel(secondCallIntent);
应该足以取消这些类型的所有警报,不需要:
firstCallIntent.cancel();
编辑:设置2个日历对象
//midday
Calendar cal1 = Calendar.getInstance();
cal1.set(Calendar.HOUR_OF_DAY, 12);
cal1.set(Calendar.MINUTE, 00);
cal1.set(Calendar.SECOND, 00);
//7pm
Calendar cal2 = Calendar.getInstance();
cal2.set(Calendar.HOUR_OF_DAY, 19);
cal2.set(Calendar.MINUTE, 00);
cal2.set(Calendar.SECOND, 00);
Calendar.getInstance()将返回一个日历对象并将其设置为当前系统时间。每个.set方法都会更改该日历对象的某个变量。所以目前如果是晚上8点,它会在当天设置12和7的警报,这是没用的。因此,如果您想在第二天进行设置,则需要使用cal1.add(Calendar.DAY_OF_MONTH,01);添加额外的一天,设置第二天的那个时间。希望这会有所帮助。