其他分享
首页 > 其他分享> > android – 无法在WorkManager中设置自定义工作服务器

android – 无法在WorkManager中设置自定义工作服务器

作者:互联网

我使用此代码设置我自己的工厂工厂:

val daggerWorkerFactory = DaggerWorkerFactory(toInjectInWorker)

val configuration = Configuration.Builder()
        .setWorkerFactory(daggerWorkerFactory)
        .build()

WorkManager.initialize(context, configuration)

执行此代码后,我可以获取WorkManager实例:

val workManager = WorkManager.getInstance()

问题是,对于在此之后创建的每个工人,我的工厂从未使用过.而是使用默认工厂.

我可以在API文档中看到方法“WorkManager.initialize”有一个注释:

Disable androidx.work.impl.WorkManagerInitializer in your manifest

我找不到任何有关如何执行此操作的信息.这是在一些旧版本的WorkManager上,他们忘了从文档中删除或这是否真的有必要?如果是这样,怎么样?

解决方法:

从WorkerManager.initialize()的文档

By default, this method should not be called because WorkManager is
automatically initialized. To initialize WorkManager yourself, please
follow these steps:

Disable androidx.work.impl.WorkManagerInitializer in your manifest In
Application#onCreate or a ContentProvider, call this method before
calling getInstance()

所以你需要在你的清单文件中禁用WorkManagerInitializer:

  <application
        //...
        android:name=".MyApplication">
        //...
        <provider
            android:name="androidx.work.impl.WorkManagerInitializer"
            android:authorities="your-packagename.workmanager-init"
            android:enabled="false"
            android:exported="false" />
    </application>

在您的自定义Application类中,初始化您的WorkerManager:

class MyApplication : Application() {

    override fun onCreate() {
        super.onCreate()
        val daggerWorkerFactory = DaggerWorkerFactory(toInjectInWorker)

        val configuration = Configuration.Builder()
            .setWorkerFactory(daggerWorkerFactory)
            .build()

        WorkManager.initialize(context, configuration)
    }
}

注意:

默认情况下,WorkerManager将添加一个名为WorkerManagerInitializer的ContentProvider,其权限设置为my-packagename.workermanager-init.

如果在禁用WorkerManagerInitializer时在Manifest文件中传递错误的权限,Android将无法编译清单.

标签:android,android-workmanager
来源: https://codeday.me/bug/20190727/1549244.html