0

I tried to set a background "service" that, every minute, triggers an activity that do some stuff. I found the Alarm Manager class and I wrote this code based on Android doc:

Intent backg = new Intent(getApplicationContext(), CheckConnectivity.class);
boolean backgRunning = (PendingIntent.getBroadcast(getApplicationContext(), 0, backg, PendingIntent.FLAG_NO_CREATE) != null);
if(!backgRunning) {
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, backg, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 60000, pendingIntent);
}

but the service is not triggered every minute, but it seems working only when the screen is off. Do you know why? What am I doing wrong?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
hteo
  • 315
  • 1
  • 4
  • 11
  • `is not triggered every minute, but working only when the screen is off`? so it is working or not? what behavior do you have? – nikis Aug 10 '18 at 12:23
  • Work only when the screen is off, but also in this case, is not triggered every minute – hteo Aug 10 '18 at 12:55

1 Answers1

1

Alarm Manager are not reliable, that's why Android introduced Job Scheduler. But you can not use Job Scheduler < 21. So Android introduced Work Manager in Android Architecture Component. Which handle your work internally by AlarmManager or JobScheduler.

Another good approach is to use Evernote's Jobs, which will use WorkManager from next version.

Finally I suggest you use Work Manager instead of AlarmManager.

Also see my explanation on Doze mode / Background restrictions.

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212
  • Job scheduler seems perfect for me, also with the limitation <21. If I set a Job every X minutes, and the Job is already running, the old Job is deleted, right? – hteo Aug 10 '18 at 12:59
  • I read some doc about them, and I prefer JobScheduler. My background task is simple. – hteo Aug 10 '18 at 14:46
  • Yes, I know. Please, answer this. If I set a Job every X minutes, and the Job is already running, the old Job is deleted, right? – hteo Aug 10 '18 at 15:02