问题
AlarmManager should be repeated every 1 minute, but repeated every 1, 2, 3 or 4 minutes.
Since the application I throw AlarmManager
public class PacienteApp extends Application {
@Override
public void onCreate() {
AlarmManager gps = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(this, GpsReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(this, 0, i, 0);
gps.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), 1000 * 60, pending);
}
}
Since BroadcastReceiver call a IntentService.
public class GpsReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent gps = new Intent(context, GpsIntentService.class);
context.startService(gps);
}
}
And intentservice execute the task
public class GpsIntentService extends IntentService {
public GpsIntentService() {
super("GpsIntentService");
}
@Override
protected void onHandleIntent(Intent intent) {
System.out.println("Intent service ejecutado");
}
}
As this occurs in the background, I have a couple of activities running in the foreground.
回答1:
As of KitKat (API 19), alarms are inexacted and batched together to preserve battery life by minimizing the number of times the device needs to wake up.
From the AlarmManager documentation for setRepeating()
:
Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose
targetSdkVersion
is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.
For more precision you will need to use setExact() and reschedule an alarm every time an alarm wakes up your app. Do so very carefully though, as setting frequent alarms (such as every 1 minute) will dramatically decrease your users' battery life.
From the setExact()
documenation:
Note: only alarms for which there is a strong demand for exact-time delivery (such as an alarm clock ringing at the requested time) should be scheduled as exact. Applications are strongly discouraged from using exact alarms unnecessarily as they reduce the OS's ability to minimize battery use.
来源:https://stackoverflow.com/questions/35901849/setrepeating-of-alarmmanager-not-respond-within-the-time-indicated