带有网络约束的WorkManager无法在android 9模拟器上运行

时间:2019-05-01 03:36:24

标签: android-9.0-pie android-workmanager

WorkManager使受网络限制的工作排队,仅在不运行android 9模拟器的情况下排队

8532-8549 D/WM-PackageManagerHelper: androidx.work.impl.background.systemalarm.RescheduleReceiver enabled
8532-8549 D/WM-SystemJobScheduler: Scheduling work ID cdded304-5021-4e94-a13c-2e0746d54a58 Job ID 0
8532-8549 D/WM-GreedyScheduler: Starting tracking for [cdded304-5021-4e94-a13c-2e0746d54a58]
8532-8549 D/WM-ConstraintTracker: NetworkStateTracker: initial state = [ Connected=true Validated=false Metered=false NotRoaming=true ]
8532-8549 D/WM-NetworkStateTracker: Registering network callback
8532-8549 D/WM-GreedyScheduler: Constraints not met: Cancelling work ID cdded304-5021-4e94-a13c-2e0746d54a58
8532-8549 D/WM-PackageManagerHelper: androidx.work.impl.background.systemalarm.RescheduleReceiver enabled
8532-8549 D/WM-SystemJobScheduler: Scheduling work ID fde1a327-10dc-4356-8145-b1f624f99d48 Job ID 1
8532-8549 D/WM-GreedyScheduler: Starting tracking for [fde1a327-10dc-4356-8145-b1f624f99d48]
8532-8549 D/WM-GreedyScheduler: Constraints not met: Cancelling work ID cdded304-5021-4e94-a13c-2e0746d54a58
8532-8549 D/WM-GreedyScheduler: Constraints not met: Cancelling work ID fde1a327-10dc-4356-8145-b1f624f99d48

编辑

fun enqueueUniqueWork() {
    WorkManager.getInstance().enqueueUniqueWork(
        App.ANONYMOUS_LOGIN,
        ExistingWorkPolicy.KEEP,
        OneTimeWorkRequestBuilder<AnonymousLoginWork>()
            .setConstraints(
                Constraints.Builder()
                    .setRequiredNetworkType(NetworkType.CONNECTED)
                    .build()
            )
            .build()
    )
}

更新

我发现在Android Pie模拟器上运行应用程序时,ConnectivityManager.activeNetwork不具有NetworkCapabilities.NET_CAPABILITY_VALIDATED功能,因此未满足网络约束。 https://android.googlesource.com/platform/frameworks/support/+/androidx-master-dev/work/workmanager/src/main/java/androidx/work/impl/constraints/controllers/NetworkConnectedController.java#49 https://android.googlesource.com/platform/frameworks/support/+/androidx-master-dev/work/workmanager/src/main/java/androidx/work/impl/constraints/trackers/NetworkStateTracker.java#118 从源代码中,我们可以看到网络约束已更改为 isConnected 和& isValidated ,这意味着当前的活动网络必须具有 NetworkCapabilities.NET_CAPABILITY_VALIDATED功能。

问题是:如何在模拟器上进行配置?

1 个答案:

答案 0 :(得分:0)

我有类似的问题。帮助我弄清问题的工具是Android Studio Logcat-WorkManager记录了为什么工作无法入队或无法开始的踪迹,这对我来说非常有用。

就我而言,事实证明我不小心从工作类构造器中删除了public访问修饰符,因此WorkManager无法实例化它。一旦创建了构造函数(当然也包括类本身)public,该工作线程就成功入队并运行了。