2

VOLUME_CHANGED_ACTION get fired multiple times for same state when i press volume down or up button.

add in androidmanifest.xml:

<receiver android:name=".VolumeSateReceiver">
           <intent-filter>
                     <actionandroid:name="android.media.VOLUME_CHANGED_ACTION" />
           </intent-filter>
       </receiver>

in VolumeSateReceiver.java:

public class VolumeSateReceiver extends BroadcastReceiver {

    Context pcontext;

    @Override
    public void onReceive(Context context, Intent intent) {
        pcontext = context;
        //check the intent something like:
        if (intent.getAction().equals("android.media.VOLUME_CHANGED_ACTION")) {
            int newVolume = intent.getIntExtra("android.media.EXTRA_VOLUME_STREAM_VALUE", 0);
            int oldVolume = intent.getIntExtra("android.media.EXTRA_PREV_VOLUME_STREAM_VALUE", 0);

               if (newVolume != oldVolume) {
                   //Toast.makeText(pcontext ,"newVolume" +newVolume + " oldVolume" + oldVolume, Toast.LENGTH_SHORT).show();
                   System.out.println("In onReceive" + "newVolume" +newVolume + " oldVolume" + oldVolume );

            }
        }
    }
}
Zoe
  • 27,060
  • 21
  • 118
  • 148
Ajay Saini
  • 21
  • 3
  • A related useful post is [here](https://stackoverflow.com/questions/6896746/is-there-a-broadcast-action-for-volume-changes/37287289#37287289) which provides a number of suggestions on how to listen for changes to the device volume, mostly using a `ContentObserver` rather than a `BroadcastReceiver` which IMO provides a more flexible implementation – Jadent Jul 15 '21 at 10:22

1 Answers1

4

This is an old question, I will still try to provide an answer for anyone interested.

It is probably because Android changed the volume for multiple streams at once.

The documentation on VOLUME_CHANGED_ACTION clearly states that it includes the stream type:

 /**
 * @hide Broadcast intent when the volume for a particular stream type changes.
 * Includes the stream, the new volume and previous volumes
 *
 * @see #EXTRA_VOLUME_STREAM_TYPE
 * @see #EXTRA_VOLUME_STREAM_VALUE
 * @see #EXTRA_PREV_VOLUME_STREAM_VALUE
 */

Android can, depending on which state (in-call, listening to music, ...) the phone is scale multiple streams on one side-button event. So you will also have to filter out any streams you're interested in, e.g. in your onReceive function:

int stream = intent.getExtras().getInt(STREAMTYPE_EXTRA);
if ((stream == AudioManager.STREAM_MUSIC) {
  //do something when music stream changed
}
Deadolus
  • 372
  • 3
  • 17