我想在特定时间设置和取消闹钟。我使用以下代码使用TimePicker进行相同的操作。
public void setRecurringAlarm(int randomTimer,long mills, int i){
Intent intent = new Intent(CreateAlarmActivity.this, AlarmReceiver.class);
intent.setData(Uri.parse("timer:" + i));
PendingIntent pendingIntent = PendingIntent.getBroadcast(CreateAlarmActivity.this, 1253, intent, PendingIntent.FLAG_CANCEL_CURRENT| Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,mills,
pendingIntent);
Toast.makeText(CreateAlarmActivity.this, "Alarm "+i+" isSet", Toast.LENGTH_LONG).show();
}
注意: - 假设我在晚上10点设置闹钟。它适用于晚上10点。但是,当我再次运行相同的代码(晚上10点之后),即一旦已经设置了警报的时间已经过去并且我记得该代码(重置警报),它立即开始运行。为什么会这样?我无法得到我错的地方。
答案 0 :(得分:2)
您可以检查闹钟时间是否在当前时间之前。如果是,则设置第二天的警报时间(如果您要至少触发一次警报,或者想要设置重复警报)。
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 0);
if (System.currentTimeMillis() > cal.getTimeInMillis()) {
calendar.add(Calendar.DATE, 1);
}
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
答案 1 :(得分:1)
public void scheduleAlarm() {
// time at which alarm will be scheduled here alarm is scheduled at 1
// day from current time,
// we fetch the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000 milliseconds in a day
// Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;
Calendar cal = Calendar.getInstance();
cal.add(Calendar.HOUR_OF_DAY, 20);
cal.add(Calendar.MINUTE, 00);
cal.add(Calendar.SECOND, 00);
Intent intent = new Intent(CreateAlarmActivity.this, AlarmReceiver.class);
// create the object
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
PendingIntent.getBroadcast(this, 1, intentAlarm,
PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled ", Toast.LENGTH_LONG)
.show();
}
希望这会对你有所帮助
答案 2 :(得分:0)
2件事:
如果你正在回忆这段代码"通过使用setRecurringAlarm(randomTimer, mills, i)
参数的相同值调用mills
,警报的时间将在过去,并且会立即触发(如果您计划过去有触发时间的警报,警报立即触发。
请从| Intent.FILL_IN_DATA
的来电中删除PendingIntent.getBroadcast()
。它并不属于那里,因为此参数应仅包含PendingIntent
个标记,并且可能会造成一些损害。