androidandroid-workmanagerlibrary-project

Initialize WorkManager custom configuration in library and host app - Android library project


I am developing a library and using a WorkManager in it with WorkManager 2.5.0
Since I want to customize WorkManager's configuration from library side, I removed workmanager-init in AndroidManifest.xml and added custom configuration like this as described as on-demand initialization in doc

<provider
        android:name="androidx.work.impl.WorkManagerInitializer"
        android:authorities="${applicationId}.workmanager-init"
        tools:node="remove" />

[in AndroidManifest.xml in my library module]

and

    WorkManager.initialize(context, Configuration.Builder().setMinimumLoggingLevel(Log.INFO).build())  

[in one of the classes in my library module]

now, it works as expected in terms of a library. However, here comes the problem when host app also wants to customize WorkManager's configuration as well.

When the host app uses WorkManager 2.5.0 as well,

    WorkManager.initialize(context, Configuration.Builder().setMinimumLoggingLevel(Log.VERBOSE).build())

App crashes with this line of a code by throwing an exception with java.lang.IllegalStateException: WorkManager is already initialized.
I tried removing workmanager-init in AndroidManifest.xml in host app but it still gives me the same error.

Is there any way for host app to customize WorkManager's configuration as well as my library customizing it?


Solution

  • WorkManager is a singleton and it can be initialized only once; or in the library or in the application.

    I would suggest to delegate WorkManager's configuration to the application following the documentation guide on this topic.