我正在制作一个警报应用程序。警报运行正常。例如,如果我将闹钟设置为 06:00 PM,它将在 06:00 PM 执行。问题是当秒恰好为零时警报不会执行。有时它在 32 秒(06:00:32 PM)运行,有时在其他秒等。
在我的主要 Activity 中,我设置了警报保存按钮,当我单击时,将执行以下代码:
buttonSetAlarm.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View arg0) {
Calendar current = Calendar.getInstance();
Calendar cal = Calendar.getInstance();
cal.set(pickerDate.getYear(),
pickerDate.getMonth(),
pickerDate.getDayOfMonth(),
pickerTime.getCurrentHour(),
pickerTime.getCurrentMinute(),
00);
if(cal.compareTo(current) <= 0){
//The set Date/Time already passed
Toast.makeText(getApplicationContext(),
"Invalid Date/Time",
Toast.LENGTH_LONG).show();
}else{
setAlarm(cal);
}
}});
主 Activity 中的SetAlarm方法是:
private void setAlarm(Calendar targetCal){
info.setText("\n\n***\n"
+ "Alarm is set@ " + targetCal.getTime() + "\n"
+ "***\n");
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), 1000*60, pendingIntent);
}
在我的 AlarmReceiver BroadCastReceiver 中,我有以下 onReceive 方法:
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
}
关于我的问题应该出在哪里的想法?
最佳答案
从 API 19 (KitKat) 开始,默认情况下警报不精确。如果您的 targetSdkVersion
设置为 19 或更高,则将使用此行为。请参阅文档中有关 AlarmManager.setRepeating()
方法的注释:
Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.
因此,最好的选择是使用精确的一次性警报,并在每次到期时相应地重新设置警报。
关于java - Android 闹钟正在运行,但秒数为零时却没有闹钟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32758849/