-1

how can i detect if volume up and down buttons are pressed simultaneously for certain period of time to perform specific task on android. I'm currently using java to develop an application which increment the count on pressing volume up and down button together for some period of time.

if(keycode == KeyEvent.KEYCODE_VOLUME_DOWN && keycode == KeyEvent.KEYCODE_VOLUME_UP) {
    // Two buttons pressed, call your function
    count++;
    String num = String.valueOf(count);
    number.setText(num);
    Toast.makeText(getApplicationContext(), "Hello", Toast.LENGTH_SHORT).show();
}

I tried this code but it didn't work

I also used boolean

while(keycode == KeyEvent.KEYCODE_VOLUME_DOWN || keycode == KeyEvent.KEYCODE_VOLUME_UP){
    if (keycode == KeyEvent.KEYCODE_VOLUME_DOWN){
        down = true;
        if(keycode == KeyEvent.KEYCODE_VOLUME_UP){
            up = true;
            if(up && down) {
                // Two buttons pressed, call your function
                Toast.makeText(getApplicationContext(), "Hello", 
                               Toast.LENGTH_SHORT).show();
            }
        }
    }
}
whiplash
  • 695
  • 5
  • 20

1 Answers1

1

Try this, it will work :

ArrayList<Integer> pressedkeys = new ArrayList<>(); 

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

    pressedkeys.add(keyCode);

    if(event.isLongPress())
    if(pressedkeys.contains(24) && pressedkeys.contains(25)) {

     //Do Something;    

    }

    return (true or false);
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    
    pressedkeys.removeAll(Collections.singleton(keyCode));
    return (true or false);
}

Return true if you handled the event and does not want anything else to happen or false if you want to allow the event to be handled by the next receiver.

Note : Please feel free to improve my answer...

You can also checkout this : Android 2 keys at a time

DrHowdyDoo
  • 2,327
  • 2
  • 7
  • 21