Tuesday, 14 March 2023

Wake up the app when there are changes in specific external storage folder in the background

I want to track changes to the user's selected external storage folder in the background without Foreground Service and wake up the app when the changes occur. This should work even if the user removes the app from recent apps. By waking up the app at this stage I mean to just send user a notification that the changes were detected. The reason I don't want to use Foreground Service is because I don't want to show a constant notification that I'm monitoring the filesystem.

I thought it wouldn't be possible with current Android restrictions, but then I ran into FolderSync app. With this app when you set up a local - remote folder pair, it tracks the changes to the local folder very accurately while not showing any notification in the status bar (meaning they are not running a Foreground Service to perform that). Please take a look at this video to see how it works (it's shot on a Samsung phone running Android 13)

I've looked into various approaches, and the only potential solution I found is to use addContentUriTrigger that WorkManager offers.

An example usage in my scenario would be:

                val folderUri = Uri.parse("file://" + folderPath)

                workRequestBuilder.setConstraints(
                    Constraints.Builder()
                        .addContentUriTrigger(folderUri, true)
                        .build()
                ).addTag(WORKER_TAG)

                workManager.enqueue(syncMonitorBuilder.build())

But it doesn't work. First, in this case, for some reason WorkManager doesn't get triggered at all. And if I replace it with .addContentUriTrigger(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, true) to listen to the changes of DCIM directory (instead of a custom directory) - WorkManager works fine while the app in recent apps, but stops once you remove the app from recent apps.



from Wake up the app when there are changes in specific external storage folder in the background

No comments:

Post a Comment