android - Android 5.1 重复任务仅在应用关闭时执行一次
问题描述
我需要每天早上 1:00 在 Android 5.1 设备上在后台执行一项艰巨的任务。不幸的是,我的AlarmManager
, JobSchedular
orWorkManager
最多执行一次任务,有时甚至一次都没有。
任务是在应用程序关闭且显示屏可能关闭时从手机中删除联系人并插入新联系人。
有人可以告诉我,即使应用程序关闭并且电话显示关闭,是否有一种始终如一的工作方式来执行重复任务?
工作经理代码:
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
,JobSchedular
或AlarmManager
特定服务中执行相同的代码
解决方案
推荐阅读
- r - 删除ggplot geom_point中单个分类y轴上方和下方的空间
- qt - qml 中的 TextField 内的矩形中不能有多个 InnerShadow
- javascript - 为什么这个图像的 React 迭代不起作用?
- reactjs - React:为什么用户刷新页面后才能退出?
- express - express firebase 服务 POST/GET 请求以 404 错误响应
- android - 在移动设备上从我的前端本地向后端发出请求的问题
- amazon-sagemaker - describe_feature_group() 字典中缺少“ResolvedOutputS3Uri”键
- database - 在多步入职中保留数据的最佳方法是什么?
- python - python-django 无法创建目录和文件
- python - python udp没有收到所有数据包