I am trying to do custom work manager initialisation. I do not want the work manager to get initialised at the beginning, I want to initialise only if login is success. But I always get the below exception even though work manager is not initialised:
java.lang.IllegalStateException: WorkManager is already initialized. Did you try to initialize it manually without disabling WorkManagerInitializer? See WorkManager#initialize(Context, Configuration) or the class level Javadoc for more information.
Below is my manifest file, I have disabled default initialisation of work manager:
<provider
tools:node="remove"
android:name="androidx.work.impl.WorkManagerInitializer"
android:authorities="${applicationId}.workmanager-init"
android:exported="false"
android:enabled="false"/>
Below is my application class, I have implemented Configuration.Provider:
open class MyApplication : Application(), Configuration.Provider {
override fun onCreate() {
super.onCreate()
daggerComponent = DaggerApplicationComponent.builder().application(this).build()
}
override fun getWorkManagerConfiguration(): Configuration {
val factory: AppWorkerFactory = daggerComponent?.factory()!!
return Configuration.Builder()
.setMinimumLoggingLevel(android.util.Log.INFO)
.setExecutor(appExecutors.upload).setWorkerFactory(factory)
.build()
}
}
I am trying to initialise the work manager as shown below in LoginFragment if login is success:
WorkManager.initialize(activity?.application as MyApplication, (activity?.application as MyApplication).workManagerConfiguration)
Please let me know what am I missing and why am I not able to initialise work manager in Login Fragment, I have not initialised work manager in any other place, but still why am I getting work manager already initialised exception?
If you are implementing On Demand Initialization by having your application implement Configuration.Provider
and override getWorkManagerConfiguration()
, then you do not need to call initialize
manually - that's precisely what On Deman Initialization is doing for you.