JobService 未在 android 9 内重新安排

JobService does not get rescheduled in android 9

我正在尝试让我的应用程序在 Android 9 上运行。以下代码在 Android 8 之前都可以正常工作,但由于某种原因,JobService 不会在 [=] 上重新安排22=] 9. 第一次被调度但是没有按照设置的periodic重新调度

class RetrieveJobService : JobService() {

override fun onStartJob(params: JobParameters): Boolean {
    doBackgroundWork(params)
    return true
}

private fun doBackgroundWork(params: JobParameters) {
    Thread {
        try {
            doRetrieveBackgroundStuff(this)
            jobFinished(params, false)
        } catch (e: Exception) {
            jobFinished(params, false)
        }
    }.start()
}

override fun onStopJob(params: JobParameters): Boolean {
    return false
}

}

这是我的 JobInfo.Builder

val builder = JobInfo.Builder(jobID, componentName)
                    .setPersisted(true)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    builder.setPeriodic(millis, 15 * 60 * 1000) //15 min
} else {
    builder.setPeriodic(millis)
}
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED)

val scheduler = context.getSystemService(JOB_SCHEDULER_SERVICE) as 
        JobScheduler
val resultCode = scheduler.schedule(builder.build())

有什么想法吗? 编辑:需要说明的是,此代码在 Android 8 及以下版本上运行良好,并且在 Android Studio 模拟器 运行 Android 9 上也能正常运行。尽我所能测试,它不适用于任何物理设备 运行 Android 9.

如果你遍历 THE LINK,你会发现:

Unfortunately, some devices implement killing the app from the recents menu as a force stop. Stock Android does not do this. When an app is force stopped, it cannot execute jobs, receive alarms or broadcasts, etc. So unfortunately, it's infeasible for us to address it - the problem lies in the OS and there is no workaround.

这是一个已知问题。许多厂商为了省电,强行关闭app,从而取消了所有的周期任务、闹钟和广播接收等。主要厂商有OnePlus(你可以选择toogle)、Redmi、Vivo、Oppo、Huwaei。

UPDATE

这些设备中的每一个都有 AutoStartManagers/AutoLaunch/StartManager 类型的优化管理器。这可以防止后台活动再次启动。您将不得不手动要求用户将您的应用程序列入白名单,以便该应用程序可以自动启动其后台进程。关注 THIS and THIS link,了解更多信息。

不同厂商加入白名单的方法在. Even after adding to whitelist, your app might not work because of DOZE Mode, for that you will have to ignore battery otimizations

此外,如果您可能想知道,Gmail/Hangout/WhatsApp/Slack/LinkedIn 等应用程序已被这些自动启动管理器列入白名单。因此,对它们的后台进程没有影响。您总是会及时收到更新和通知。