Taking over the volume key on Android

后端 未结 3 1755
眼角桃花
眼角桃花 2020-12-09 13:56

I want to take overinput over the Volume Up and Down. At the moment my code is:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    Log.v(         


        
3条回答
  •  萌比男神i
    2020-12-09 14:38

    It's important to return true if you handled the event, but if you didn't handle the event, it's good to make sure that the event is still handled by the superclass. Here's some code from my app:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
            keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            changeColor(keyCode);
    
            return true;
        }
    
        return super.onKeyDown(keyCode, event);
    }
    
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
            keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            // do nothing                                                       
    
            return true;
        }
    
        return super.onKeyUp(keyCode, event);
    }
    

    In my case, the superclass call was necessary so that other hardware buttons on my device continued to work.

提交回复
热议问题