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

730 views Asked by At

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?

2

There are 2 answers

0
pfmaggi On BEST ANSWER

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.

0
Marc Calandro On

By reading the description of the method you are using you would had the answer .

"Used to do a one-time initialization of the WorkManager singleton with a custom Configuration. By default, this method should not be called because WorkManager is automatically initialized. To initialize WorkManager yourself, please follow these steps:

Disable androidx.work.WorkManagerInitializer in your manifest. Invoke this method in Application#onCreate or a ContentProvider. Note that this method must be invoked in one of these two places or you risk getting a NullPointerException in getInstance(Context).

This method throws an IllegalStateException when attempting to initialize in direct boot mode.

This method throws an exception if it is called multiple times."