Volume Control in android application

I'd like to know how to control my application's volume from the volume keys (contrary to my belief , I've read they control only the ringer volume). Should I overwrite the onKey Down/Up?

Or is there other way to accomplish this? I'm asking because if I overwrite the upper mentioned function for an activity, then the functions will receive the event only if a view associated with the this activity has the focus, and I'm looking for something "Globaly" ( to work no matter what activity is running now)


Solution 1:

There was another question from a long time ago that asked the same thing. Essentially the answer is: don't override the onKeyDown and onKeyUp buttons. It's much better to simply use this one line setVolumeControlStream(AudioManager.STREAM_MUSIC); in your onCreate() method. That tells the OS that the volume buttons should affect the "media" volume when your application is visible, and that's the volume it uses for your application.

As for controlling the Media volume no matter what app is visible, I'm not sure that can be done - or if it could, whether that would be a good thing.

Solution 2:

In your activity you can use one of the following:

this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
this.setVolumeControlStream(AudioManager.STREAM_RING);  
this.setVolumeControlStream(AudioManager.STREAM_ALARM);  
this.setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);  
this.setVolumeControlStream(AudioManager.STREAM_SYSTEM);  
this.setVolumeControlStream(AudioManager.STREAM_VOICECALL);