我的 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_WAKEUP
和 AlarmManager.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/