首页 > 解决方案 > Android 5.1 重复任务仅在应用关闭时执行一次

问题描述

我需要每天早上 1:00 在 Android 5.1 设备上在后台执行一项艰巨的任务。不幸的是,我的AlarmManager, JobSchedularorWorkManager最多执行一次任务,有时甚至一次都没有。
任务是在应用程序关闭且显示屏可能关闭时从手机中删除联系人并插入新联系人。

有人可以告诉我,即使应用程序关闭并且电话显示关闭,是否有一种始终如一的工作方式来执行重复任务?

工作经理代码:

PeriodicWorkRequest repeatingWorkRequest = new PeriodicWorkRequest.Builder(RepeatingWorker.class, 24, TimeUnit.HOURS)//
                    .setInitialDelay(millisTilOneAm, TimeUnit.MILLISECONDS)//
                    .build();
WorkManager.getInstance(getApplicationContext())//
                    .enqueueUniquePeriodicWork("repeatingworker",//
                            ExistingPeriodicWorkPolicy.REPLACE, //
                            repeatingWorkRequest);  

报警管理器代码:

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); 

Job Schedular 的执行不能“延迟”并在 1 个调用内重复。
这就是为什么我创建了DelayedService一个重复作业在上午 01:00 开始的
JobSchedular 代码:

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");
}  

延迟服务代码:

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);

Worker,JobSchedularAlarmManager特定服务中执行相同的代码

标签: androidscheduled-tasksalarmmanagerandroid-jobschedulerandroid-5.1.1-lollipop

解决方案


推荐阅读