Enable Media Volume In Android Application
Posted by admin on
May 22, 2012
So you want your Android application to be able to change the media volume settings when the user presses the hard key volume buttons on the phone.
The way to do this is to make sure that your Activity class gets a reference of the audio service and override the OnKeyDown() method and catch the keypress event.
Check out the following code:
// call this in your Activity's onCreate(), make sure the variable is global. AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE); @Override public boolean onKeyDown(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: audio.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI); return true; default: return false; } }






