I am developing an android app and have an operation that occurs repeatedly, even when the app is closed. I use android's AlarmManager
to schedule the repeated event as follows:
Broadcast Receiver code (relevant part):
@Override
public void onReceive(Context context, Intent intent){
this.lastContext = context;
Log.i("Instructions", "Getting instructions...");
Session.device = (Device)intent.getExtras().get("device");
Session.user = (User)intent.getExtras().get("user");
Session.data = (Data)intent.getExtras().get("data");
Session.deviceManager = (DevicePolicyManager)context.getSystemService(Context.DEVICE_POLICY_SERVICE);
Session.compAdmin = new ComponentName(context, ControlAdmin.class);
new ApiRequest(Api.makeDeviceRequest("instruction.php")).builder()
.addOption("username", Session.user.getUsername())
.addOption("password", Session.user.getPassword())
.addOption("device_id", Session.device.getNetId())
.setCallback(this)
.execute();
}
The above code simply sends a GET request to an online API to download a string which contains some information for the device.
This is how I register the broadcast receiver with the AlarmManager:
private static final int REQUEST_CODE = 48432;
public static void register(Context context, Class<? extends BroadcastReceiver> receiver, long delay, long interval, String[] keys, Parcelable[] objects){
Intent intent = new Intent(context, receiver);
if(keys != null && objects != null)
for(int i = 0; i < keys.length && i < objects.length; i++)
intent.putExtra(keys[i], objects[i]);
PendingIntent sender = PendingIntent.getBroadcast(context, REQUEST_CODE, intent, 0);
long firstTime = System.currentTimeMillis() + delay;
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, firstTime, interval, sender);
}
How I use the register method above:
register(context, InstructionsReceiver.class, 0L, 5000L, new String[] { "user", "device", "data" }, new Parcelable[] { Session.user, Session.device, Session.data });
The broadcast receiver does receive broadcasts but not at 5 second intervals as I have written in the example above. Instead, the intervals are random above 60 seconds. I don't understand why this is happening.
Is this normal (says irregular intervals in AlarmManager docs > API 19)? If not, what have I done wrong?