问题描述
我用这个代码来设置我自己的工人工厂:
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:
在清单中禁用 androidx.work.impl.WorkManagerInitializer
我找不到有关如何执行此操作的任何信息.这是在一些旧版本的 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()
默认情况下,不应调用此方法,因为 WorkManager
是自动初始化.要自己初始化 WorkManager
,请请按照以下步骤操作:
在清单中禁用 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()
所以你需要的是在你的 Manifest 文件中禁用 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 中设置自定义工人工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!