Android N 中的定期作业(牛轧糖,7.0)

Periodic Job in Android N (Nougat, 7.0)

好的,所以我找不到关于此的任何文档或有用的网页。帮助我 Whosebug,你是我唯一的希望。

好的,原来我的 JobScheduler 看起来像这样:

JobScheduler scheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
if(scheduler.getPendingJob(JOB_NUMBER) == null) {
    ComponentName componentName = new ComponentName(this, MyJobService.class);
    JobInfo info = new JobInfo.Builder(JOB_NUMBER, componentName)
            .setRequiresCharging(false)
            .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
            .setPersisted(true)
            .setPeriodic(60 * 60 * 1000L, 5 * 60 *1000)
            .build();
    int resultCode = scheduler.schedule(info);
    if (resultCode == JobScheduler.RESULT_SUCCESS) {
        Log.d(TAG, "Service is not running, Job " + String.valueOf(JOB_NUMBER) + " Scheduled.");
    } else {
        Log.d(TAG, "Service is not running, However job scheduling failed.");
    }
} else{
    Log.d(TAG, "Service is already scheduled.");
}

...在 Oreo (v8.0) 中完美运行。但是在 Nougat v7.0 中,作业得到 'scheduled' 但永远不会 运行。在我问的另一个 Whosebug 问题中,我发现我可以通过将 setPeriodic() 替换为以下内容来获得它 运行:

.setMinimumLatency(1 * 1000)
.setOverrideDeadline(3 * 1000)

然后,服务 运行s。但是,这不是周期性的,它只会 运行 一次。我找不到允许我在 Android 牛轧糖中 运行 定期工作的文档/教程/示例。谁能帮我解决这个问题?

关于这个完全相同的主题还有其他 Whosebug 问题:

Job Scheduler Not recurring in periodic in Android 7.0 (Nougat)

然而他们都没有明确的答案。

最后一分钟注意:好吧,似乎将 FlexMillis 传递给 setPeriodic() 似乎有效。我要做更多的测试。当 logcat 被触发时,我不确定我正在 运行ning 什么代码,但我想通过传递:

.setPeriodic(15 * 60 * 1000, 5 * 60 *1000)

进入 setPeriodic 它在作业安排后 10 分钟触发。但是,与 Oreo 不同的是,该作业在首次安排时并未 运行。在 Oreo 中,我一构建作业,作业就是 运行。同样,我在文档中的任何地方都找不到这个。

你应该使用 https://developer.android.com/topic/libraries/architecture/workmanager/。这是新的 Android 工具,它根据情况使用 JobScheduler/AlarmManager 等等。