Skip to content Skip to sidebar Skip to footer

Where To Register A Contentobserver Which Must Run Indefinitely?

Here is how I am registering a ContentObserver to listen to sent sms: SendSmsObserver smsObeserver = (new SendSmsObserver(new Handler(), context)); ContentResolver contentResolver

Solution 1:

You could create a service that runs indefinitely in the background (Start sticky). In this service you can add your content observer (first 3 lines). This way you ensure that the service is still working after the user closes the app.

You can start this service in the OnCreate of your application class, and also in the broadcast receiver to make sure that it runs after the phone is rebooted.

Solution 2:

You should put those 3 lines of code in a foreground service.

Running a service in the background and keeping it "sticky" no longer works in newer version of Android for your scenario. The system will kill your background service eventually if your main app has been destroyed. The only way that has worked for me is to run a foreground service, which means there is a permanent notification. With this method, I was able to have my contentobserver run indefinitely as long as the foreground service was running.

I am still looking for a way to run a background service forever, and just fyi the following link does not work, Android will send a couple of broadcasts to restart service but eventually it will fail due to trying to start that service too many times.

https://fabcirablog.weebly.com/blog/creating-a-never-ending-background-service-in-android

Post a Comment for "Where To Register A Contentobserver Which Must Run Indefinitely?"