In my application I start a service containing a fileobserver to monitor a directory. My problem is that after a while the service is interrupted and if you wake up the phone the service starts again. I also tried to hook the observer file to a static variable inside the service but it still does not work. Who can give me an example of fileobserver executed inside a service started when the phone is booted and not interrupted when the phone falls asleep?
Services were never meant to run forever and this behaviour is most likely caused by doze mode and if you are running on API level 26 or higher there are stricter restrictions for background services.
You could run a foreground service (which needs a permanent notification to inform the user that your app is running) but even foreground services are not safe to be not killed when the system decides to do so.
For your use case you could have a look at the Work Manager from the Jetpack Components. It offers a method to schedule a Job when a content URI changes: addContentUriTrigger()
Sample Code:
// first define a worker - this will get called by the WorkManager and
// performs the code you put in doWork()
class YourWorker(context : Context, params : WorkerParameters)
: Worker(context, params) {
override fun doWork(): Result {
//your code
}
}
// add your content uri as a constraint trigger
val constraints = Constraints.Builder()
.addTriggerContentUri(YOUR_CONTENT_URI)
.build()
// create a request for the WorkManager
var req : OneTimeWorkRequest = OneTimeWorkRequestBuilder<YourWorker>()
.setConstraints(constraints)
.build()
// push your request to the WorkManager
WorkManager.getInstance().enqueue(req)
The official Codelab from Google is a good way to get better understanding of the concepts: Background Work with WorkManager