4

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);
Ton
  • 9,235
  • 15
  • 59
  • 103

2 Answers2

1

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

Aditya
  • 5,509
  • 4
  • 31
  • 51
0

For the purpose you can also use a broadcast receiver:

Register this in Manifest:

<receiver android:name="MyClass" >
    <intent-filter>
        <action android:name="android.media.VOLUME_CHANGED_ACTION" />
    </intent-filter>
</receiver>

Use this code in MyClass.java:

@Override
public void onReceive(Context context, Intent intent) {
    Var_Volume_Value = (Integer) intent.getExtras().get("android.media.EXTRA_VOLUME_STREAM_VALUE");
}
FireAphis
  • 6,650
  • 8
  • 42
  • 63
Ankit Jain
  • 2,230
  • 1
  • 18
  • 25