在我的任务应用程序中,我想为多个项目创建警报服务。这是我创建服务时遵循的代码。让我们假设,如果列表中存在超过5个项目。然后我们将发送5次不同的报警服务。
如果用户来编辑时间怎么办?,如何更新系统并确保它在新实例中触发?如果用户删除任务,如何快速删除已删除任务的已注册alram,该怎么办? 如何卸载应用程序?,如何清除所有条目?,如果系统重新启动怎么办?
这是我在alram服务中注册任务的代码
Calendar Calendar_Object = Calendar.getInstance();
Calendar_Object.set(Calendar.MONTH, 8);
Calendar_Object.set(Calendar.YEAR, 2012);
Calendar_Object.set(Calendar.DAY_OF_MONTH, 6);
Calendar_Object.set(Calendar.HOUR_OF_DAY, 14);
Calendar_Object.set(Calendar.MINUTE, 25);
Calendar_Object.set(Calendar.SECOND, 0);
Step 2:
We need to create an alarm which help us to invoke the BroadCastReceiver on our specified time.
// MyView is my current Activity, and AlarmReceiver is the BoradCastReceiver
Intent myIntent = new Intent(MyView.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
MyView.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
/*
The following sets the Alarm in the specific time by getting the long value of the alarm date time which is in calendar object by calling the getTimeInMillis(). Since Alarm supports only long value , we're using this method.
*/
alarmManager.set(AlarmManager.RTC, Calendar_Object.getTimeInMillis(),
pendingIntent);
答案 0 :(得分:1)
使用此方法设置闹钟:
public static void startAlarm(Context context, int alarm_code, String time) {
String[] arrTime = time.split(":");
intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("CODE", alarm_code);
PendingIntent mAlarmSender = PendingIntent.getBroadcast(context,
alarm_code, intent, 0);
Calendar cal_alarm = Calendar.getInstance();
cal_alarm.setTimeZone(TimeZone.getDefault());
cal_alarm.set(Calendar.HOUR_OF_DAY, Integer.parseInt(arrTime[0]));
cal_alarm.set(Calendar.MINUTE, Integer.parseInt(arrTime[1]));
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, mAlarmSender);
}
此处,"int alarm_code"
是您对特定项目的唯一代码。
并且对于更新警报首先取消现有警报并为新时间设置新警报。为此使用此方法:
public static void cancelAlarm(Context context, int alarm_code) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("CODE", alarm_code);
am.cancel(PendingIntent.getBroadcast(context, alarm_code, intent, 0));
}
此处,"int alarm_code"
将是您用于设置闹钟的唯一代码。因此,具有特定alarm_id的闹钟将被取消。您也可以使用此方法删除闹钟。
同样,您可以清除所有将alarm_code传递给给定函数的警报。
您必须为系统重新启动注册接收器,并且在onReceive注册表中您必须再次设置所有警报。
希望这会对你有所帮助。