java - 每天在特定时间启动服务

标签 java android service alarmmanager

我制作了一个日历,在每天晚上 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/

相关文章:

wcf - 从 WCF Web 服务访问 HttpContext.Current

android - 如何在 Android 服务中启动没有标志 FLAG_ACTIVITY_NEW_TASK 的 Intent ?

java - 获取一组颜色的平均值

java - 在android中无需单击按钮即可查看实例

java - 使用 Apache Camel ProdcerTemplate 和 CxfComponent 发送多个参数作为 requestBody

android - 具有不同渐变的自定义背景颜色

android - ConstraintLayout 在底部工作 TableView 中无法正常工作

java - Android 通知监听器服务自行启动

java - HTMLPanel 可以在 uiBinder 中使用,即使它没有无参数构造函数。怎么会?

java - 在 Java Web 应用程序中处理 X-FORWARDED-PROTO header