WorkManager Side Effects: A Follow-Up

About two months ago, I wrote about how WorkManager has side effects. Notably, it triggers the system to send ACTION_PACKAGE_CHANGED broadcasts to your app. At best, those broadcasts might confuse your code that is expecting those broadcasts to be sent for other reasons, such as components that you are enabling or disabling yourself. At worst, we wind up in an infinite loop, if you try scheduling work as part of handling such a broadcast… which includes scheduling work from onUpdate() of an AppWidgetProvider.

I argued that WorkManager should provide options to avoid or manage that side effect.

Google disagreed.

This side effect, and any others, seem to be undocumented. Apparently, blog posts from balding authors suffices.

So, you need to be a bit careful about your use of WorkManager:

  • If your app responds to ACTION_PACKAGE_CHANGED broadcasts, directly or indirectly, it may not be safe to schedule work there, lest you wind up in the infinite loop scenario that I described in my earlier post.

  • If your app responds to ACTION_BATTERY_OK, ACTION_BATTERY_LOW, ACTION_POWER_CONNECTED, ACTION_POWER_DISCONNECTED, ACTION_DEVICE_STORAGE_LOW, ACTION_DEVICE_STORAGE_OK, CONNECTIVITY_CHANGE, ACTION_TIME_SET, or ACTION_TIMEZONE_CHANGED, bear in mind that WorkManager has receivers for those broadcasts in your app. These are all disabled at the outset, but presumably WorkManager has code to enable them based on certain conditions, such as certain constraints that you set in your work requests. Be careful about scheduling work with WorkManager on those broadcasts as well.

  • If your app responds to ACTION_BOOT_COMPLETED broadcasts, bear in mind that WorkManager also depends on this broadcast. Your respective receivers might be invoked in any order. It may not be safe to schedule work here, as WorkManager might assume that its own ACTION_BOOT_COMPLETED receiver has completed its work by the time you try scheduling new work. While I would not expect an infinite loop scenario, this is the sort of edge case that requires a lot of testing to ensure everything will work as expected.

  • WorkManager has a ContentProvider that it bakes into your app as well. While scheduling your own work from onCreate() of a ContentProvider would be rather odd, it’s possible that somebody might want to do that. Be careful, as WorkManager may not be fully ready for operation at that point. Note that, last time I tested it, all ContentProvider instances are created before onCreate() of Application, so probably it is safe to schedule work there.

There may be other edge and corner cases beyond these. So, while WorkManager is nice, make sure that you thoroughly test your use of it.