I have been trying to schedule an Android service to run repeatedly using the AlarmManager class, but the service stops being called after a couple of days. Originally I had been using the below code to try and achieve this:
Intent alarmIntent = new Intent(currentActivity.getApplicationContext(), AlarmReceiver.class);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(currentActivity.getApplicationContext(),
AppManager.ALARM_PENDING_INTENT_REQUEST_CODE,
alarmIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)currentActivity.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(),
interval,
pendingAlarmIntent);
with the receiver:
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context _context, Intent _intent){
Intent serviceIntent = new Intent(_context.getApplicationContext(), PostLocationService.class);
_context.getApplicationContext().startService(serviceIntent);
}
}
This worked for a few days and then suddenly stopped. So I changed the code to initially broadcast to the receiver once and then re broadcast to the receiver each time the Service is run. I did this with the following code:
Intent alarmIntent = new Intent(currentActivity.getApplicationContext(), AlarmReceiver.class);
PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(currentActivity.getApplicationContext(),
AppManager.ALARM_PENDING_INTENT_REQUEST_CODE,
alarmIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager)currentActivity.getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,
interval,
pendingAlarmIntent);
Unfortunately this has the same result; the Service stops being executed after a couple of days.
I have also registered a receiver for when the device boots to re initiate the AlarmManager call which is the same code as above.
Am I missing something? Is there a better approach than either of the above methods for this type of constant repetitive execution?