I'm making an app that needs to do some tasks repeteadly, usually between 1 and 5 minutes.
I have tried .setRepeating
, setInexactRepeating
and .set
(the last one re-setting the alarm when the task is done)
When the alarm fires a service is started.
Usually it works well, but sometimes the alarm suddenly stops firing, no matter what method I use.
I have tested in Android 5.1 and 4.4.2.
Why is this happening? Is this a known bug or something?
Here is the method I use to set the alarm, the commented code is the other method I tried:
public void setAlarm(Context context) {
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
/*alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + 1000,
PreferenceHelper.readLong(PreferenceHelper.PREF_TIME_TO_REFRESH), alarmIntent);*/
alarmMgr.set(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + PreferenceHelper.readLong(PreferenceHelper.PREF_TIME_TO_REFRESH), alarmIntent);
ComponentName receiver = new ComponentName(context, BootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
As I said before, if I use .set
I call the method again when the service finishes the asigned task. (This works too, but again the alarm suddenly stops firing after a few hours).
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, WifiCheckerService.class);
startWakefulService(context, service);
}