I need to execute a huge task in the Background every day at 01:00 a.m. on an Android 5.1 device.
Unfortunately my AlarmManager, JobSchedular or WorkManager is executing the Task at maximum once, sometimes not even once.
The Task is to delete Contact's from the phone and insert new ones while the App is closed and the Display may be off.
could someone tell me, if there is a consistently working way to execute a reapeating task even if the App is closed and the Display of the Phone is off?
WorkManager Code:
PeriodicWorkRequest repeatingWorkRequest = new PeriodicWorkRequest.Builder(RepeatingWorker.class, 24, TimeUnit.HOURS)//
.setInitialDelay(millisTilOneAm, TimeUnit.MILLISECONDS)//
.build();
WorkManager.getInstance(getApplicationContext())//
.enqueueUniquePeriodicWork("repeatingworker",//
ExistingPeriodicWorkPolicy.REPLACE, //
repeatingWorkRequest);
AlarmManager Code:
Intent intent = new Intent(getApplicationContext(), RepeatingService.class);
intent.putExtra("IS_REPEATING", inRepeating);
PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), inRepeating ? 10000 : 12345, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendarTilOneAm.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
The Job Schedular's execution can't be "delayed" and repeated within 1 call.
That is why I created a DelayedService in which a Repeating Job is started at 01:00 a.m.
JobSchedular Code:
ComponentName componentName = new ComponentName(MainActivity.this, DelayedJobService.class);
JobInfo jobInfo = new JobInfo.Builder(2, componentName)//
.setPersisted(true)//
.setMinimumLatency(millisTilNightSync)//
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(jobInfo);
if (resultCode == JobScheduler.RESULT_SUCCESS) {
long seconds = millisTilNightSync / 1000;
System.err.println("Job executes within: " + seconds + " seconds");
}
DelayedService Code:
ComponentName componentName = new ComponentName(this, RepeatingJobService.class);
int twentyFourHours = 1000 * 3600 * 24;// 1k ms * 3,6k sek = 1h * 24 = 24h
JobInfo jobInfo = new JobInfo.Builder(3, componentName)//
.setPersisted(true)//
.setPeriodic(twentyFourHours)
.build();
JobScheduler jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
int resultCode = jobScheduler.schedule(jobInfo);
Within the Worker, JobSchedular or AlarmManager specific Service the same Code executes