问题
I want the users to be able to longpress the volumeUp hardware button for skipping a song, and do the regular volumeUp action on a short press.
I'm able to differentiate between both (I found this solution, working with flags between onKeyDown, onKeyLongPress and onKeyUp) but I'm wondering if I can still call the standard/super action when the volume up button has been pressed. I can't seem to figure out when the volumeUp action is being called (in the onKeyDown- or onKeyUp-event) and where to call it.
Or should I just write my own function to change the volume?
Thanks.
My code:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
event.startTracking();
if (bLong) {
bShort = false;
return true;
} else {
bShort = true;
bLong = false;
return true;
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
if (bShort) {
bShort = false;
bLong = false;
if (mp != null) {
//HERE IS WHERE I WANT TO CALL THE VOLUME-UP ACTION
}
return true;
}
}
return super.onKeyUp(keyCode, event);
}
@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
if (bRunning && mp != null) {
playNextSong();
}
bShort = false;
bLong = false;
return true;
}
return super.onKeyLongPress(keyCode, event);
}
回答1:
Take a look maybe this gonna help you.
public boolean dispatchKeyEvent(KeyEvent event) {
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN && event.isLongPress()) {
//(skipping a song)
}
if (action == KeyEvent.ACTION_UP) {
//(vol up)
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_UP)
return true;
default:
return super.dispatchKeyEvent(event);
}
}
来源:https://stackoverflow.com/questions/14958701/how-to-catch-longpress-and-call-the-standard-action-on-keycode-volume-up