问题
I am trying to set a background service with alarm manager.
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.cancel(pending);
//alarmManager.SetExact(AlarmType.RtcWakeup, SystemClock.ElapsedRealtime() + 5 * 1000, pendingIntent);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,SystemClock.elapsedRealtime()+15*1000 , 15*1000, pending);
But it is not working every 15 seconds. Sometimes works after 20 seconds, sometimes after 1 minute. But, When I set 1 minute(60*1000)it is not also the exact time. it's close.(1 minute 4 second, 1 minute 13 second) Why is that happing?
回答1:
Repeating alarms are by default inexact since API 19.
A workaround is to set a simple exact alarm in x seconds and then set another alarm recursively when the alarm is triggered. This code works for me like a charm. All you need to do in addition is define the service in your XML:
<receiver android:name=".AlarmReceiver" android:process=":remote" />
From the main activity you start it like this:
AlarmReceiver alarm = new AlarmReceiver();
alarm.setAlarm(this);
The service in which you schedule the alarm is the same in which it is also received:
public class AlarmReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
setAlarm(context);
//Put whatever you want to do below here
}
public void setAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, (System.currentTimeMillis()/1000L + 5L) *1000L, pi); //Next alarm in 5s
}
}
来源:https://stackoverflow.com/questions/59425417/alarm-manager-set-repeating-is-not-repeating-under-1-minute