Kali C
Kali C

Reputation: 23

Accessibility Service onKeyEvent

I'm trying to mute all sounds threw Accessibility Service, is that possible?

if not can I manage the volume keys? I am currently using onKeyEvent to get all volume key events, and it is working fine but I would like to disable the volume keys in a certain condition and enable them in other condition. I have failed to make this happened because it behaves in a strange way which don't listen to my condition and either works or not. The following code is an example of what I got:

@Override
public boolean onKeyEvent(KeyEvent event) {

    int action = event.getAction();
    int keyCode = event.getKeyCode();
    if(CONDITION) {
        if (action == KeyEvent.ACTION_UP) {
            if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
                return false; // Volume key shouldn't work
            }
            return true; // execute key normally
        }
    }
    return true; // Volume key should work
}

in this case the volume keys don't work no matter what the CONDITION is. and if I change one of the returns to return super.onKeyEvent(event) suddenly the volume key work all the time despite the CONDITION :( I don't know what to do

Please Help, Any advise would help.

Thanks in advance!:)

Upvotes: 0

Views: 577

Answers (1)

Kali C
Kali C

Reputation: 23

Hey the problem was that the function only consumed the action = ACTION_UP while it triggers both action_up and action_down so the volume keys always worked, now I have changed it to consume both actions and it works! the code is:

@Override
public boolean onKeyEvent(KeyEvent event) {

    int action = event.getAction();
    int keyCode = event.getKeyCode();
    if(CONDITION) {
        if (action == KeyEvent.ACTION_UP || action == KeyEvent.ACTION_DOWN) {
            if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
                return true; // Volume key don't work
            }
        }
    }
    return false; // Volume keys work
}

Hope it helps anyone. :)

Upvotes: 1

Related Questions