Getting what has changed in ContentObserver

Ton picture Ton · May 31, 2013 · Viewed 8k times · Source

I want to know if the volume has changed. Reading other post I found this code to register a ContentObserver and get an event when something changes. My problem is that I don't know how to know what has changed. I mean, I get an OnReceive() but how can I get the extra information (what volume key was pressed, for example).

I also get a lot of unneeded events, for example, clicking on the "Menu" button triggers this event too, but nothing has changed (yet).

This is my code.

Thank you

public class clsSettingsContentObserver extends ContentObserver
{
   public Context Contexto=null; //This is for displaying Toasts

   public clsSettingsContentObserver(Handler handler)
   {  super(handler);
   } 


   @Override public boolean deliverSelfNotifications()
   {
      return super.deliverSelfNotifications(); 
   }


   @Override public void onChange(boolean selfChange)
   {  super.onChange(selfChange);

      //How do I get more info here?????
      ShowToast("Settings change detected");    
   }


   private void ShowToast(String strMensaje)
   {  Toast toast1 = Toast.makeText(Contexto, strMensaje, Toast.LENGTH_SHORT);
      toast1.show();   
   };

}

And this is how I register it:

clsSettingsContentObserver oSettingsContentObserver = new clsSettingsContentObserver( new Handler() );
oSettingsContentObserver.Contexto = this; //This is for displaying Toasts
getApplicationContext().getContentResolver().registerContentObserver(
            android.provider.Settings.System.CONTENT_URI,
            true, 
            oSettingsContentObserver);

Answer

Aditya picture Aditya · Jun 3, 2013

Register the content observer using

getApplicationContext().getContentResolver().registerContentObserver(
        android.provider.Settings.System.CONTENT_URI,
        false, 
        oSettingsContentObserver);

This will stop unwanted notifications from descendants of the database. See public final void registerContentObserver (Uri uri, boolean notifyForDescendents, ContentObserver observer) for more details