问题描述
我使用以下代码来设置自己的工人工厂:
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)
执行此代码后,我可以获取WorkManager实例:
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.
我可以在API文档中看到"WorkManager.initialize"方法有一条注释:
I can see in the API documentation that the method "WorkManager.initialize" has a note:
我找不到有关如何执行此操作的任何信息.这是在某些较旧版本的WorkManager上,他们忘了从文档中删除吗,或者这真的有必要吗?如果可以,怎么办?
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?
推荐答案
来自 WorkerManager.initialize()
在清单中禁用 androidx.work.impl.WorkManagerInitializer
Application#onCreate
或 ContentProvider
,请在调用此方法之前调用 getInstance()
Disable androidx.work.impl.WorkManagerInitializer
in your manifest In Application#onCreate
or a ContentProvider
, call this method before calling getInstance()
因此,您需要在清单文件中禁用 WorkManagerInitializer
:
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>
然后在您的自定义 Application
类中,初始化您的 WorkerManager
:
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)
}
}
注意:
默认情况下, WorkerManager
将添加名为 WorkerManagerInitializer
的 ContentProvider
,其权限设置为 my-packagename.workermanager-init 代码>.
By default, WorkerManager
will add a ContentProvider
called WorkerManagerInitializer
with authorities set to my-packagename.workermanager-init
.
如果您在禁用 WorkerManagerInitializer
时在清单文件中传递了错误的权限,则Android将无法编译清单.
If you pass wrong authorities in your Manifest file while disabling the WorkerManagerInitializer
, Android will not be able to compile your manifest.
这篇关于无法在WorkManager中设置自定义工人工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!