How to control media volume?

I haven't tried this but you should be able to intercept the regular volume buttons by overriding onKeyDown(int keyCode, KeyEvent event) in your Activity. Check for keycodes KEYCODE_VOLUME_UP and KEYCODE_VOLUME_DOWN.

Using AudioManager.setStreamVolume(int, int, int) with STREAM_MUSIC for the streamType parameter should work and if you return true from the onKeyDown(...) method (to indicate you've handled the event), it should prevent the system from adjusting the ringer volume. Make sure you return false for all other keycodes that you're not handling.


Please don't handle the volume keys yourself - it is almost impossible to guarantee that you won't break the behavior of the volume keys.

Call this API in your onCreate():

setVolumeControlStream(AudioManager.STREAM_MUSIC);

This tells the AudioManager that when your application has focus, the volume keys should adjust the music volume.


In your activity's onCreate() you can do:

setVolumeControlStream(AudioManager.STREAM_MUSIC);

Tags:

Android