chathura
chathura

Reputation: 3452

Unable to initiate WorkManager from a separate process

I'm using the WorkManager library(version: 1.0.0-alpha12). In my app I'm creating a new process using the below xml line in AndroidManifest.

android:process=":myprocess"

This is how I use the WorkManager:

 public static void startCheckStatusWorker() {
    WorkManager manager = WorkManager.getInstance();
    String uniqueName = "check_status_worker";
    PeriodicWorkRequest.Builder builder = new PeriodicWorkRequest.Builder(CheckStatusWorker.class, 1, TimeUnit.DAYS);
    builder.setConstraints(new Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build());
    PeriodicWorkRequest request = builder.build();
    manager.enqueueUniquePeriodicWork(uniqueName, ExistingPeriodicWorkPolicy.KEEP, request);
 }

But when I call this method from the new process, then the app crashes. This is the exception thrown,

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.
at androidx.work.WorkManager.getInstance(WorkManager.java:139)

If I call the same method, from the normal app process it works well and I don't disable the WorkManagerInitializer in my app manifest as it suggests.

Is there a way to get the WorkManager instance from the new process?

Any suggestion would be appreciated. Thanks.

Upvotes: 1

Views: 4589

Answers (1)

edy
edy

Reputation: 452

If you REALLY REALLY need the service to be in a separate process, you can disable the WorkManagerInitializer in the AndroidManifest. Goes something like this:

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

(For the official documentation refer to https://developer.android.com/topic/libraries/architecture/workmanager/advanced/custom-configuration#java)

After disabling it , in your Application class (if you don't have one you should create your own and extend the android Application class), and call WorkManager.initialize().

That fixed it for me.

But please note, according to some answers in the google issues forums(https://issuetracker.google.com/issues/79993883), the workmanager will still use the main-process in order to do work (even if it's called from a second process).

What I recommend? If there is no serious advantage from having the service on a non-main-process, you should just make the service be on the main process since it would be harder to maintain (for example static global vars will have two instances, one for each process)

Upvotes: 2

Related Questions