0

I need to have my application listen for changes in addressbook in Android. I have read that it can be done using ContentObserver and listening for changes in ContactsContract.Contacts. It seems the lifecycle of the ContentObserver ends when the application is closed.

How do I make the ContentObserver work even if the application wasn't opened?

MikkoP
  • 4,864
  • 16
  • 58
  • 106

2 Answers2

1

How do I make the ContentObserver work even if the application wasn't opened?

That is not possible. The point behind a ContentObserver is to be notified of changes that might affect a running app, such as changes to data that need to be reflected in an activity showing that data. If your app is not running, you cannot have a ContentObserver.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • What other options do I have in terms of listening for changes in addressbook? – MikkoP Oct 08 '13 at 13:54
  • @MikkoP: Ideally, you stop listening for real-time changes in whatever "addressbook" is and solve your problem in some other way. You are welcome to use things like foreground services to try to keep your app in memory, and your users are welcome to then force stop or uninstall your app and give you nasty comments on the Play Store in response. – CommonsWare Oct 08 '13 at 14:00
  • I'm not sure about you, but I think address book is pretty well known term when speaking about the database that contains all the user's contacts. Do you think it's better to have a button in the application to refresh the contacts after a change has been made? I don't and I don't think that a user would even remember to do that. And concidering that I'm the only user, I'm pretty sure about that ;) – MikkoP Oct 08 '13 at 14:08
0

register your Content Observer in the OnStartCommand with return START_STICKY; instead of registering it in the onCreate. It works for me.

@Override  
public int onStartCommand(Intent intent, int flags, int startId) {  
    getContentResolver().registerContentObserver(uri,true, new SMSObserver(new Handler(), getBaseContext())); 
    return START_STICKY;    
} 
eldarerathis
  • 35,455
  • 10
  • 90
  • 93