Wednesday, April 24, 2013

Use Android’s ContentObserver in Your Code to Listen to Data Changes such as contact change.

ContentObserver make some work easier, such if you want to track by your own sdk application suppose when your contacts being changed, you can easily do that.

To use the ContentObserver you have to take two steps:
  • Implement a subclass of ContentObserver
  • Register your content observer to listen for changes 

Implement a subclass of ContentObserver

ContentObserver is an abstract class with no abstract methods. Its two onChange() methods are implemented without any logic. And since these are called whenever a change occurs, you have to override them.
Since Google added one of the two overloaded onChange() methods as recently as API-level 16, this method’s default behavior is to call the other, older method.
Here is, what a normal implementation would look like:

class MyObserver extends ContentObserver {       
   public MyObserver(Handler handler) {
      super(handler);           
   }

   @Override
   public void onChange(boolean selfChange) {
      this.onChange(selfChange, null);
   }       

   public void onChange(boolean selfChange, Uri uri) {
      System.out.println("HMM");
   }       
}

Also notice the Handler parameter in the constructor. This handler is used to deliver the onChange() method. So if you created the Handler on the UI thread, the onChange() method will be called on the UI thread as well. In this case avoid querying the ContentProvider in this method. Instead use an AsyncTask or a Loader.
If you pass a null value to the constructor, Android calls the onChange() method immediately – regardless of the current thread used. I think it’s best to always use a handler when creating the ContentObserver object.

Register your content observer to listen for changes

To register your ContentObserver subclass you simply have to call the ContentResolver's registerContentObserver() method:

getContentResolver().registerContentObserver(Phone.CONTENT_URI, true, new MyObserver(null));

It takes three parameters. The first is the URI to listen to. I cover the URI in more detail in the next section.
The second parameter indicates whether all changes to URIs that start with the given URI should trigger a method call or just changes to exactly this one URI. This can be handy for say the ContactsContract URI with its many descendants. But it can also be detrimental in that the actual change, that caused the method call, is even more obscure to you.
The third parameter is an instance of your ContentObserver implementation.

 

No comments:

Post a Comment