Search code examples
javaandroidillegalstateexceptionandroidxandroid-workmanager

IllegalStateException: WorkManager is already initialized


Having these dependencies:

dependencies {
    implementation "androidx.work:work-runtime:2.0.1"
    androidTestImplementation "androidx.work:work-testing:2.0.1"
}

When running this code for the second time:

Configuration config = new Configuration.Builder().build();
WorkManager.initialize(getApplicationContext(), config);

this.workManager = WorkManager.getInstance();

I get this error message:

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.

and it also throws a segmentation fault on the native side:

A/libc: Fatal signal 11 (SIGSEGV), code 1 (SEGV_MAPERR),
fault addr 0x878 in tid 10892 (ova.workmanager),
pid 10892 (ova.workmanager)

This would be the documentation for WorkManager#initialize(Context, Configuration).


The intent is to prevent the crash during manual initialization (in order to change the log level). How to disable the WorkManagerInitializer? If possible, I do not want to use the static keyword.


Solution

  • This is how to substitute provider androidx.work.impl.WorkManagerInitializer:

    <application>
        ...
    
        <!-- disable default provider -->
        <provider
            android:name="androidx.work.impl.WorkManagerInitializer"
            android:authorities="${applicationId}.workmanager-init"
            android:exported="false"
            android:enabled="false"/>
    
        <!-- register custom provider -->
        <provider
            android:name=".CustomWorkManagerInitializer"
            android:authorities="${applicationId}.WorkManagerInit"/>
    
    </application>
    

    Source: Custom Work Manager initialization (in Kotlin).


    Unless registering another provider, this gives a:

    java.lang.IllegalStateException: WorkManager is not initialized properly. The most
    likely cause is that you disabled WorkManagerInitializer in your manifest but forgot
    to call WorkManager#initialize in your Application#onCreate or a ContentProvider.
    

    And the ContentProvider registered in the src/debug/Manifest.xml:

    public class WorkManagerInit extends ContentProvider {
    
        @Override
        public boolean onCreate() {
            if(getContext() != null) {
                Configuration config = new Configuration.Builder().build();
                WorkManager.initialize(getContext().getApplicationContext(), config);
            }
            return true;
        }
        ...
    }