androidcontentobserver

register/unregister `ContentObserver` for events far apart in time


Scenario :

I want to register a ContentObserver when user logs-in, and unregister it, when user logs-out. The ContentObserver#onChange() starts a service that syncs data with server.

Question :

The method to unregister ContentObserver is ContentResolver#unregsiterContentObserver() but this method needs

previously registered observer that is no longer needed

How to do that ? the login and logout events are far apart in time, how do I keep reference (or maybe retrieve using some method ?) to that same ContentObserver object ?


Solution

  • How to do that ?

    You need to arrange to hold onto that ContentObserver instance somewhere that will live as long as you need it. For example, you might need to hold onto it in a static field.