Android WorkManager PeriodicWorkRequest issue -- not running after app is closed

1.3k views Asked by At

I have been trying to migrate from Firebase Job Dispatcher to androidx Work Manager. My app was working well with Job Dispatcher. The problem with Work Manager is that it doesn't execute the Periodic Work after the app is closed. Without Periodic Work running, users cannot receive notifications.

My app is being tested on several Pixel Emulators (e.g. SDK Level 30) launching from Android Studio. I expected stock Android behavior from those emulators. I also tested by using physical phones and got the same problem.

I have been searching for the solution but so far without luck. Could you help identifying the cause and the solution?

Here is my Java code:

    Constraints constraints = new Constraints.Builder()
            .setRequiredNetworkType(NetworkType.CONNECTED)
            .build();

    PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(MyClass.class, 15, TimeUnit.MINUTES)
            .addTag("my_tag")
            .setConstraints(constraints)
            .setInitialDelay(15, TimeUnit.MINUTES)
            .build();

    WorkManager.getInstance(appContext)
            .enqueueUniquePeriodicWork("my_unique_work_name", ExistingPeriodicWorkPolicy.REPLACE, periodicWorkRequest);

    Log.d ( "From Work scheduling procedure...", "periodicWorkRequest enqueued" );

Here is my configuration in build.gradle (app level)

    implementation 'androidx.work:work-runtime:2.4.0'
1

There are 1 answers

3
autumnmaple On

After searching for the answer for over a day, I got it by having many rounds of trial and error. The issue is not about my program but a specific behavior of Logcat.

After I closed my app on an emulator, I noticed that the Logcat's process drop-down menu showed "No debuggable processes". That was the reason I couldn't see my debugging messages or the related Periodic Work messages logged. When I re-launched the app, my app re-appeared as the debuggable process in the drop-down menu, and all the Periodic Work items executed earlier appeared in Logcat.

For a phone that I tested, after I closed my app on it while having the USB cable connected, I noticed that the Logcat's process drop-down menu remained having my app as the debuggable process. I became more patient waiting and observing. My debugging messages for Periodic Work appeared.

My Periodic Work items were actually being executed on my emulators and phones. I didn't see the logs in Logcat and I assumed my program was not working well. My program was working well but I didn't understand Logcat enough.

I came across many similar questions when I was searching for the answer. Hopefully my answer helps saving some of you some time.

Logcat drop-down menus