Java – Observe the volume changes made by the application

Observe the volume changes made by the application… here is a solution to the problem.

Observe the volume changes made by the application

I have a ContentObserver registered with android.provider.Settings.System and should observe any changes in volume. I get a notification as expected when I click the hardware volume button, but I don’t get a notification when I change the audio volume via AudioManager.setStreamVolume or AudioManager.adjustStreamVolume.

This is what my ContentObserver looks like:

// this is a Service
this.getApplicationContext().getContentResolver().registerContentObserver(
  android.provider.Settings.System.CONTENT_URI, 
  true, new ContentObserver(new Handler()) {
    public void onChange(boolean selfChange) {
      Log.d("ContentObserver", "got notified");
    }
});

Here is my call to AudioManager.adjustStreamVolume:

// this.context is the activities context
this.context.getSystemService(Context.AUDIO_SERVICE).adjustStreamVolume(
  AudioManager.STREAM_RING, AudioManager.ADJUST_LOWER,
  AudioManager.FLAG_SHOW_UI);

I’ve read this and that post and AudioManager and Settings.System documentation and can’t find why Observer is notified when the volume is changed using the volume buttons and not when changing the volume using AudioManager.

Thanks for your help!

Solution

AudioManager does broadcast an intent

android.media.VOLUME_CHANGED_ACTION`

But this is not part of the official documentation. So this may change in a future release. But you can at least use it for Gingerbread devices.

You can find it in find more information about additional features in the intent here

Related Problems and Solutions