尝试使用Pending Intent设置多个警报,但是警报不会在正确的时间内广播。可能是什么导致了这个?
public void clicker (View view)
{
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(AddAlarm.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker,
int selectedHour, int selectedMinute) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, selectedHour);
calendar.set(Calendar.MINUTE, selectedMinute);
int c_hour,c_min;
String format;
c_hour=selectedHour;
c_min=selectedMinute;
if (c_hour == 0) {
c_hour += 12;
format = "AM";
} else if (c_hour == 12) {
format = "PM";
} else if (c_hour > 12) {
c_hour -= 12;
format = "PM";
} else {
format = "AM";
}
String formatTime = String.format("%02d : %02d %s", c_hour, c_min, format);
TextView dimple = (TextView)findViewById(R.id.timeText);
dimple.setText(formatTime);
setAlarm(calendar);
}
}, hour, minute, false);// Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
private void setAlarm(Calendar targetCal)
{
Intent alarmintent = new Intent(AddAlarm.this, AlarmReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(AddAlarm.this, pen, alarmintent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), sender);
}
这就是我设置闹钟的方法,还有待处理的意图被设置为系统时间,以ms为单位,logcat中没有警告或错误,报警工作正常,唯一的问题是没有及时,预计一到两分钟延迟?有什么建议吗?
答案 0 :(得分:0)
在Calendar.getInstance();
中使用onTimeSet
后使用calendar.setTimeInMillis(System.currentTimeMillis());
也许这会有所帮助。还要确保在多个警报的情况下对待处理意图使用不同的requestCodes
答案 1 :(得分:0)
自API级别19以来,警报默认不准确。你可以改用setExact()方法。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
am.setExact(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), sender);
} else {
am.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), sender;
}
您可以在此处找到更多信息: http://developer.android.com/reference/android/app/AlarmManager.html#setExact%28int,%20long,%20android.app.PendingIntent%29