android - AlarmManager不会在特定时间触发

标签 android alarmmanager

我的 AlarmManager 有问题。我可以使用此代码设置警报

private void setAlarm(long when) {
    Intent intent = new Intent(NoteActivity.this, AlarmReceiver.class);
    intent.putExtra("ID", note.getId());
    AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, when, PendingIntent.getBroadcast(NoteActivity.this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT));
    Toast.makeText(getApplicationContext(),"Reminder set up", Toast.LENGTH_SHORT).show();
}

如果我设置 long when = 5 * 1000; ,此代码可以很好地工作;\\例如 5 秒后,但如果我使用此代码

Calendar calendar = Calendar.getInstance();
                    calendar.setTime(date);
                    long selectedDate = date.getTime();
                    long timeSince1970 = System.currentTimeMillis();
                    long timeForAlarm = selectedDate - timeSince1970;

                    Intent intent = new Intent(NoteActivity.this, AlarmReceiver.class);
                    intent.putExtra("ID", note.getId());
                    AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
                    manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, timeForAlarm, PendingIntent.getBroadcast(NoteActivity.this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT));
                    Toast.makeText(getApplicationContext(),"Reminder set for "+calendar.getTime().toString(), Toast.LENGTH_SHORT).show();

我的闹钟在 2 秒后触发。我做错了什么? :/ 我已尝试 AlarmManager.ELAPSED_REALTIME_WAKEUPAlarmManager.RTC_WAKEUP 但没有任何改变。

请不要检查我的问题是否重复。我没有找到可以解决我的问题的方法。

最佳答案

假设您正在使用 Android Studio(如果不是 - 您必须切换),请在文本指针位于 set 方法上时单击 F1 并阅读 AlarmManager::set 的说明。

Note: Beginning in API 19, the trigger time passed to this method is treated as inexact: the alarm will not be delivered before this time, but may be deferred and delivered some time later. The OS will use this policy in order to "batch" alarms together across the entire system, minimizing the number of times the device needs to "wake up" and minimizing battery use. In general, alarms scheduled in the near future will not be deferred as long as alarms scheduled far in the future.

关于android - AlarmManager不会在特定时间触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41446964/

相关文章:

java - 从 2 个 TimePicker 获取值并进行比较

android - 使用 expo kit 在 React Native 中加载自定义原生组件

android - Android list 中的 strings.xml 冲突

android - 使用自定义适配器填充 ListView

android - Android 中使用 AlarmManager 的多个警报?

android - 警报管理器即使在重新启动后仍然存在吗?

Android SDK - 设置具有相同 Intent 不同附加功能的多个警报

android - 在我的应用程序关闭后执行 RxAndroid Observables

android - 手机关机时的 AlarmManager - ANDROID

android - 关闭设备 Android 后警报不会触发通知