在这本section的有关安排重复警报的Android开发文档中,“如果您指定的触发时间是过去的时间,则警报将立即触发”。因此,如果现在是上午9点,并且我将AlarmManager设置为在上午8点执行我的每日通知,则它不会等到明天上午8点执行通知,它会立即弹出。如何使其不弹出?
这是我的评论代码:
/**
* Show alertDialog to pick time
* @param v
*/
@Override
public void onClick(View v){
Calendar c=Calendar.getInstance();
mHour=c.get(Calendar.HOUR_OF_DAY);
mMinute=c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog=new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int hour, int
minute) {
timeSet.setText(hour+":"+minute);
//storing the inputted hour and time, so they reappear when
//app reopens
editor.putInt("Hour",hour);
editor.putInt("Minute",minute);
editor.apply();
scheduleNotification(hour,minute);
}
},mHour,mMinute,true);
timePickerDialog.show();
}
/**
*Building Intent for AlarmReceiver and PendingIntent.
* Give PendingIntent to AlarmManager
* @param hour user-inputted hour of day
* @param minute user-inputted minute of day
*/
public void scheduleNotification(int hour, int minute){
Intent intent1=new Intent(this,AlarmReceiver.class);
//FLAG_UPDATE_CURRENT: if the described PendingIntent already exists,
//keep it but replace its extra data with what is in this new Intent.
PendingIntent pendingIntent=PendingIntent.getBroadcast(this
,0
,intent1
,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am=(AlarmManager)this.getSystemService(this.ALARM_SERVICE);
Calendar calendar=Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,hour);
calendar.set(Calendar.MINUTE,minute);
//RTC_WAKEUP: wake up the device when it goes off.
am.setRepeating(AlarmManager.RTC_WAKEUP
, calendar.getTimeInMillis()
,AlarmManager.INTERVAL_DAY
,pendingIntent);
}
AlarmReceiver.class用于在接收电话时发出通知,并接收未决的Intent并使用它来调用AlarmReceiver.class(以进行通知)。
答案 0 :(得分:0)
您可以添加带有您的特定时间和当前时间的校验码:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY,hour);
calendar.set(Calendar.MINUTE,minute);
long _alarm = 0;
Calendar now = Calendar.getInstance();
if(calendar.getTimeInMillis() <= now.getTimeInMillis())
_alarm = calendar.getTimeInMillis() + (AlarmManager.INTERVAL_DAY+1);
else
_alarm = calendar.getTimeInMillis();
am.setRepeating(AlarmManager.RTC_WAKEUP
, _alarm
,AlarmManager.INTERVAL_DAY
,pendingIntent);