2

Are content observers persistent in Android? If I create a content observer in an activity, will that observer continue to run until I remove the observer.

Basically I am creating a service for SMS, where on receive and on send I post the SMS out to a web service, so I can check my messages with out having my phone.

If the content observer is tied to the Activity's life, how can I create a ContentObserver that will always receive notifications on content:/sms/

Lucas Stark
  • 131
  • 2
  • 11

2 Answers2

6

If I create a content observer in an activity, will that observer continue to run until I remove the observer.

Only if you like leaking memory, and then only until Android terminates the process. Well-behaved activities will not register content observers without unregistering them at an appropriate time (e.g., onDestroy()).

how can I create a ContentObserver that will always receive notifications on content:/sms/

The SMS content provider is not part of the SDK. It may or may not work on your phone. It may or may not work in future versions of Android.

The only way to have a ContentObserver that sticks around for a bit is to have it be in a Service. However, services do not live forever, either. Beyond that, there is no way to have an observer "always receive notifications".

Sorry!

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • Is what way would it be considered leaked memory if your intention is to have a persistent content observer? Just like a broadcast receiver. And if I understand you correctly, a content observer has a better chance of surviving for longer if it's registered through a service which is (as much as possible) persistently running than just registering the observer and not keeping a reference to it, e.g., directly in the `onReceive()` method of a broadcast receiver after boot? – Reti43 Feb 20 '17 at 00:08
  • @Reti43: "Is what way would it be considered leaked memory if your intention is to have a persistent content observer?" -- you would not do that from an activity. "And if I understand you correctly..." -- correct, though on Android 7.0+, you can use `JobScheduler` to observe the content for you, invoking your `JobService` when there are changes. – CommonsWare Feb 20 '17 at 00:16
0

I have tried many ways to make this work, the only way (non-ideal) that has worked is to have a foreground service which runs even after your activity is destroyed. The foreground service registers the contentobserver. the downside is foreground services require a permanent notification.

I am still looking for a way to have a background service run without it being recycled, and it gets harder and harder. Stuff like "sticky" and broadcast receiver to restart service are no longer working.

Bqin1
  • 467
  • 1
  • 9
  • 19