Search code examples
androidandroid-jobschedulerandroid-background

Schedule Job for file change notifications


I want to be notified when a specific file changes. I was looking into FileObserver but after having read the answer in this thread, I've tried to accomplish my target with a JobScheduler that should run the job when the file changes, using addTriggerContentUri().

I started by copying the example from the documentation page, changing the Uri that should trigger the job to Uri.fromFile(File(<path-to-file>)). Unfortunately, my onStartJob() method is never called although JobScheduler::schedule() returns success.

Now, I am wondering if I've done anything wrong or if there is a general flaw in my interpretations, maybe it is just impossible to trigger a job on ordinary file changes?

The stripped-down version of my class/code looks like this (Kotlin):

class FilechangeService : JobService() {

    companion object {

        private const val JOB_ID = 0

        // Schedule this job, replace any existing one.
        fun scheduleJob(context: Context) {

            // JobInfo Builder to construct the Job
            val builder = JobInfo.Builder(
                JOB_ID,
                ComponentName(context, FilechangeService::class.java)
            )
            // Look for changes to specific file
            val uri = Uri.fromFile(File(<path-to-file>))
            builder.addTriggerContentUri(
                JobInfo.TriggerContentUri(uri, 0)
            )
            val jobInfo = builder.build()
            val js = context.getSystemService(JobScheduler::class.java)
            val status = js.schedule(jobInfo)
        }
    }

    override fun onStartJob(params : JobParameters) : Boolean {
        // Code that is never executed =(
        return false
    }
}

Of course, FilechangeService::scheduleJob() is called from an other part of my application. Furthermore, I have added the Service to my AndroidManifest.xml with android:permission="android.permission.BIND_JOB_SERVICE".

Thanks in advance for any help!


Solution

  • To sum up what has been said in the comments, it seems to be impossible to do what I tried to achieve. This is due to the fact that the Uri has to be a "content Uri", so a "file Uri" seems to be invalid.