问题
I scheduled alarm using Calendar class as below
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY,1);
cal.getTimeInMillis();
cal.set(Calendar.MINUTE,05);
long TriggerMillis = cal.getTimeInMillis();
AlarmManager aManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
aManager.set(AlarmManager.RTC_WAKEUP, TriggerMillis,pIntent);
where pIntent is an pending intent to proceed further when alarm triggers.
The event triggers with few seconds delay. Is that any problem using Calendar class for this task. Any suggestions?
TIA..
回答1:
You have two issues:
It is not reliable to use a
_WAKEUP
alarm with a service directly. The only reliable patterns involveWakefulBroadcastReceiver
, myWakefulIntentService
, or something along those lines, where thePendingIntent
will be to aBroadcastReceiver
.If your
android:targetSdkVersion
is 19 or higher, and you are running on an API Level 19+ device,set()
is inexact. Ideally, you allow it to be inexact, or perhaps usesetWindow()
to control how off it will be, to minimize the power hit of your alarm event. If it absolutely has to occur at a precise moment, you will need to usesetExact()
. SincesetWindow()
andsetExact()
are new to API Level 19, you will need to fall back toset()
on older devices, by examiningBuild.VERSION.SDK_INT
and branching accordingly.
来源:https://stackoverflow.com/questions/21355348/alarm-manager-not-triggering-alarms-at-exact-time-in-android