Sunday, 24 April 2022

OneTimeWorkRequest (content observer) loses first picture after app is closed. Works OK for subsequent pictures

I am trying to implement reliable background listener on user media (e.g. if user takes a picture, I want to capture that, even if application is closed). I am using Android's WorkManager (OneTimeWorkRequest).

Everything works fine when application is at the foreground or in the background in the task bar. However when I close the application, doWork() doesn't gets called for the first picture that user is taking. Subsequent pictures, 2nd, 3rd and so on work just fine.

When app is closed, after first picture is taken, I can see plenty additional stuff in Logcat, almost like if Android rebuilt the app context, initialize some stuff, but actually doesn't run the doWork(), event gets lost.

Logs after first background event triggered:

...
2022-03-31 11:56:24.842 10616-10616/com.my.app I/s.app: The ClassLoaderContext is a special shared library.
2022-03-31 11:56:24.998 10616-10616/com.my.app D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2022-03-31 11:56:24.998 10616-10616/com.my.app D/NetworkSecurityConfig: No Network Security Config specified, using platform default
2022-03-31 11:56:25.000 10616-10616/com.my.app D/WM-WrkMgrInitializer: Initializing WorkManager with default configuration.
2022-03-31 11:56:25.008 10616-10616/com.my.app I/TetheringManager: registerTetheringEventCallback:com.my.app
2022-03-31 11:56:26.793 10616-10632/com.my.app W/System: A resource failed to call close. 

I get the feeling that this issue has something related to WorkManager initialization. It seems it's not properly initialized during first event. It gets initialized on the go by default initializer, however it loses the event as doWork() isn't called properly.

Any idea why this might be and how to overcome this issue?

CODE EXAMPLE

https://github.com/tomekit/so_71691180

In order to reproduce:

  1. Open this in Android Studio, compile and install app on emulator.
  2. Open camera and take a photo, you should see: I/ContentURI: content://media/external/images/media/109 in LogCat.
  3. Close an app (swipe away) and make sure it's no longer available in taskbar.
  4. Take a photo. You will see no log is produced.
  5. Take another photo. Now you can see that logs are created correctly, meaning that doWork() gets executed. Any subsequent photo, creates log entry correctly.


from OneTimeWorkRequest (content observer) loses first picture after app is closed. Works OK for subsequent pictures

No comments:

Post a Comment