Unable to set a custom worker factory in WorkManager

爷,独闯天下 提交于 2019-12-18 05:06:14

问题


I use this code to set my own worker factory:

val daggerWorkerFactory = DaggerWorkerFactory(toInjectInWorker)

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

WorkManager.initialize(context, configuration)

After this code execution, I can get the WorkManager instance:

val workManager = WorkManager.getInstance()

The problem is that for every worker created after this point, my factory is never used. The default factory is used instead.

I can see in the API documentation that the method "WorkManager.initialize" has a note:

Disable androidx.work.impl.WorkManagerInitializer in your manifest

I cannot find any information on how to do this. Was this on some older versions of the WorkManager and they forgot to remove from the documentation or is this really necessary? If so, how?


回答1:


From the documentation of 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()

So what you need is to disable WorkManagerInitializer in your Manifest file:

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

And in your custom Application class, initialize your WorkerManager:

class MyApplication : Application() {

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

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

        WorkManager.initialize(context, configuration)
    }
}

Note:

By default, WorkerManager will add a ContentProvider called WorkerManagerInitializer with authorities set to my-packagename.workermanager-init.

If you pass wrong authorities in your Manifest file while disabling the WorkerManagerInitializer, Android will not be able to compile your manifest.



来源:https://stackoverflow.com/questions/52700557/unable-to-set-a-custom-worker-factory-in-workmanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!