Reputation: 313
I am developing an Android application, and my apps will play out an alarm once it is started, but I would like to disable the external volume buttons so that when the phone is alarming, user is not able to turn down the alarm volume. I have tested on my phone with Android version 2.3.5, but it is not working. Below is my coding. Hope someone can help me... Thanks.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event){
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP){
Toast.makeText(this, "Volume Up", Toast.LENGTH_LONG).show();
return true;
}
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
Toast.makeText(this, "Volume Down", Toast.LENGTH_LONG).show();
return true;
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 5
Views: 11218
Reputation: 574
just return true to disable volume operations. and now you can do other operations from onVolumeDown() and onVolumeUp() functions.
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_VOLUME_DOWN)
onVolumeDown();
if(keyCode==KeyEvent.KEYCODE_VOLUME_UP)
onVolumeUp();
return true;
//return super.onKeyDown(keyCode, event);
}
Upvotes: 0
Reputation: 38092
The best way is to play alarm sound on one audio stream (AudioManager.STREAM_ALARM) and make volume button to be associated with another audio stream (setVolumeControlStream(AudioManager.STREAM_MUSIC);
). http://developer.android.com/training/managing-audio/volume-playback.html#HardwareVolumeKeys
Upvotes: 0
Reputation: 75644
Try overriding dispatchKeyEvent(KeyEvent event)
:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
boolean result;
switch( event.getKeyCode() ) {
case KeyEvent.KEYCODE_VOLUME_UP:
case KeyEvent.KEYCODE_VOLUME_DOWN:
result = true;
break;
default:
result= super.dispatchKeyEvent(event);
break;
}
return result;
}
also see this article.
Upvotes: 12