我制作了一个日历,在每天晚上 8:00 的特定时间显示 toast 但应用程序显示启动服务并在不同的时间显示 toast。 喜欢
8:00 pm
8:23 pm
8:30 pm
8:32 pm
8:50 pm
并且不会停止显示 toast
出了什么问题?
这是我的 Mainactivity.java 代码
Intent alarmIntent = new Intent(MainActivity.this, MyService.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 0, alarmIntent, 0);
setAlarm();
}
private void setAlarm() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
/* Set the alarm to start at 8.00 PM */
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 20);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
//Add a day if alarm is set for before current time, so the alarm is triggered the next day
if (calendar.before(Calendar.getInstance())) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), TimeUnit.MILLISECONDS.convert(1, TimeUnit.DAYS), pendingIntent);
}}
最佳答案
来自 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.
编辑 您的闹钟不准确,这意味着系统不会在您设置的 00:800 的确切时间唤醒来满足您的请求,而是会将一些需要完成的操作分组,在您设置的时间附近的某个时间,并将它们全部触发以节省手机电池,并防止手机每隔几秒单独唤醒一次。
您可以使用 AlarmManager.set()
将调用替换为非重复调用,并自行处理重复,因为每个警报触发都会安排下一个警报。
或者,如果您的警报触发对时间要求不高(不必非常精确),您可以保持原样。
关于java - 每天在特定时间启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47955856/