问题
I use setAlarmClock
method of Alarmmanager
for do alarm clock application.
When I set alarm clock from 6.00 AM and alarm in 6.01 AM . It delay and not exact.
Code when setAlarmClock
.
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra(AppConstant.REMINDER, note.convertToString());
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(),
note.getId(), intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(getTargetTime().getTimeInMillis(),pendingIntent),pendingIntent);
}
Code when setCalander for alarm
private Calendar getTargetTime() {
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.DAY_OF_MONTH, sDay);
calSet.set(Calendar.HOUR_OF_DAY, sHour);
calSet.set(Calendar.MINUTE, sMinute);
calSet.set(Calendar.SECOND, 0);
calSet.set(Calendar.MILLISECOND, 0);
return calSet;
}
Ok, I implement from this project https://github.com/googlesamples/android-DirectBoot.
This project use setAlarmClock for alarm when it's time.
update: I change setAlarmClock to setExact
This code:
alarmManager.setExact(AlarmManager.RTC_WAKEUP, getTargetTime().getTimeInMillis(), pendingIntent);
It doesn't work for me but It delay same setAlarmClock.
Current Time in millisecond: 1473318858628 I change to default format by use http://www.ruddwire.com/handy-code/date-to-millisecond-calculators/#.V9EPXfmLRD8
Thu Sep 08 2016 14:14:18 GMT+0700
Set Alarm Time in millisecond:1473318960000
Thu Sep 08 2016 14:16:00 GMT+0700
And now It's 14:16:00 , It doesn't alarm.
It's alarm on 14.20:00 , so delay about 4 minutes. ( Time in millisecond = 1473319200207)
Thank
回答1:
You should read the documentation. This is by design as according to the documentation with the excerpt:
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.
Ref
https://developer.android.com/reference/android/app/AlarmManager.html
来源:https://stackoverflow.com/questions/39363500/setalarmclock-not-exact-in-android-marshmallow