Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking over the volume key on Android

Tags:

android

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(TAG, event.toString());
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
        mLamp.moveBackward();

        return false;
    }
    else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
        mLamp.moveForward();

        return false;
    }

    return true;
}
public boolean onKeyUp(int keyCode, KeyEvent event) {

    Log.v(TAG, event.toString());
    if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
        return false;
    }
    else if(keyCode == KeyEvent.KEYCODE_VOLUME_UP){
        return false;
    }

    return true;
}

This triggers the mLamp.moveBackward() and mLamp.moveForward() function but it still changes the volume of the ringer. What do I have to do that the ringer loudness doesn't change?

like image 354
Christian Avatar asked Jul 10 '10 19:07

Christian


2 Answers

If you handled the event, return true. If you want to allow the event to be handled by the next receiver, return false.

like image 66
zed_0xff Avatar answered Nov 15 '22 08:11

zed_0xff


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.

like image 21
vor23 Avatar answered Nov 15 '22 06:11

vor23