KeyEvent.KEYCODE_VOLUME_UP(DOWN) registering double hits
android, button, volume
Solution
KeyEvent can represent multiple actions, specifically both ACTION_DOWN and ACTION_UP. Since you aren't checking the action in your dispatchKeyEvent callback you are calling your button click methods for both DOWN and UP events on the volume buttons. Try like this:
public boolean dispatchKeyEvent(KeyEvent event){
int keyCode = event.getKeyCode();
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
onButtonUp();
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
onButtonDown();
return true;
default:
return super.dispatchKeyEvent(event);
}
}
}
Problem
I have a simple app where I do the following: ``` public void onClick(View v){ switch(v.getId()) { case R.id.buttonup: onButtonUp(); break; case R.id.buttondown: onButtonDown(); break; } } public boolean dispatchKeyEvent(KeyEvent event){ int keyCode = event.getKeyCode(); switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_UP: onButtonUp(); return true; case KeyEvent.KEYCODE_VOLUME_DOWN: onButtonDown(); return true; default: return super.dispatchKeyEvent(event); } } void onButtonUp(){ increment_some_static_class_variable; } void onButtonUp(){ decrement_some_static_class_variable; } ``` The thing is, whenever I press volume buttons, the onButtonUp and onButtondown functions are called twice. This does not happen when I press on screen buttons (handled in onClick(View)). I didn't find anybody having this issue so I am asking the folks here. I am new to Android and this is my first Application. Using Log, I found that both calls to onButtonUp and onButtonDown are coming from dispatchKeyEvent function. What could be wrong here? I hope I explained the problem well. Suggestions/Solutions are most welcome.