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?
This method is deprecated. Gets a LiveData of the last time all work was cancelled. Gets a ListenableFuture of the WorkInfo for a given work id.
Stay organized with collections Save and categorize content based on your preferences. To get started using WorkManager, first import the library into your Android project. Once you've added the dependencies and synchronized your Gradle project, the next step is to define some work to run.
WorkManager is intended for work that is required to run reliably even if the user navigates off a screen, the app exits, or the device restarts. For example: Sending logs or analytics to backend services. Periodically syncing application data with a server.
From the documentation of WorkerManager.initialize()
By default, this method should not be called because
WorkManager
is automatically initialized. To initializeWorkManager
yourself, please follow these steps:Disable
androidx.work.impl.WorkManagerInitializer
in your manifest InApplication#onCreate
or aContentProvider
, call this method before callinggetInstance()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With