0

I need to implement fileObserver in background, so if new file arrives in observed directory, a notification will have to be triggered. Considering the background limitation implemented from Oreo, easiest option is just to launch fileObserver in foreground service (with notification) and keep listening. However this will keep my app in battery drainers list and I would prefer avoiding adding notification all the time. Another solution is to implement scheduler in workmanager, but this will need me reading the whole directory very frequently ( in every minute or even less time) just to identify if any new file has arrived. This means I will avoid using fileObserver but will keep consuming precious resource unnecessarily every minute.

I am hoping if someone could suggest if there is any other more efficient way to implement the functionality of fileObserver guaranteeing the functionality but keeping the resource usage at the least.

userabc55478
  • 61
  • 1
  • 8

1 Answers1

0

You can use WorkManager or JobScheduler with content URI triggers. That’s the best way to do this.

Rahul
  • 19,744
  • 1
  • 25
  • 29
  • Problem with this solution is - every time the job runs, I will have to read whole list of file names ( and their metadata ) to identify which files are newly created after last run. This is quite a waste of device resources which I am trying to avoid. Can you please make it more clear in what sense this is "the best way ? – userabc55478 Apr 22 '19 at 02:47
  • What do you mean. The ListenableWorker is already provided with the information about which Uris were triggered. Won't that tell you everything you need to know ? – Rahul Apr 22 '19 at 17:30
  • https://developer.android.com/reference/androidx/work/ListenableWorker.html#getTriggeredContentUris() – Rahul Apr 22 '19 at 17:45
  • How do you know the uri ( with file name) when you are not listening the fileobserver ? Yes, worker knows about the directory- but i need to know file name for my action and that is the main problem i am looking on. – userabc55478 Apr 23 '19 at 05:30
  • When you observe a directory (via a ContentUriTrigger) WorkManager will give you the actual uris (inside the directory) that were responsible for the trigger as part of executing the Worker. So, if you were trying to implement a Photos like sync-ing feature, you would watch the Media URIs and schedule a Worker by specifying trigger for descendents = True. – Rahul Apr 23 '19 at 20:01