Android实现组合键监听功能

时间:2022-12-16 22:39:43

有关组合监听的思路:两个键的点击其实是有先后顺序的,要先做第一个键点击的记录,如有时间要求还得记录时间。

下面是两个例子的代码:

例子1:长按音量变大的键,再按回退键一次,处发要处理的事件。

boolean isKeyvolume=false;

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int eventAction = event.getAction();
int keyCode = event.getKeyCode();
if (eventAction == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
isKeyvolume=true;
}else if(eventAction == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_VOLUME_UP){
isKeyvolume=false;
}else if(eventAction == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK){
if(isKeyvolume){
Toast.makeText(MainActivity.this,"000",Toast.LENGTH_LONG).show();
return true;
}
}
return super.dispatchKeyEvent(event);
}


例子2:长按音量变大的键,再长按回退键,处发要处理的事件。(长按时这个事件会触发多次,如果没有做双击退出应用就会出现退出应用的效果)

int mBackKeyAction, mVolumnUpKeyAction;
long mActionTime;

@Override
public boolean dispatchKeyEvent(KeyEvent event) {

int keyCode = event.getKeyCode();
int action = event.getAction();

if (keyCode == KeyEvent.KEYCODE_VOLUME_UP && event.getAction() == KeyEvent.ACTION_DOWN) {
mVolumnUpKeyAction = KeyEvent.ACTION_DOWN; //记录按下状态
if (mActionTime == 0) {
mActionTime = System.currentTimeMillis();
}
} else if (keyCode == KeyEvent.KEYCODE_VOLUME_UP && event.getAction() == KeyEvent.ACTION_UP) {
mVolumnUpKeyAction = KeyEvent.ACTION_UP; //记录松下状态
mActionTime = 0;
}else if (keyCode == KeyEvent.KEYCODE_BACK && action == KeyEvent.ACTION_DOWN) {
mBackKeyAction = KeyEvent.ACTION_DOWN; //记录按下状态
if (mActionTime == 0) {
mActionTime = System.currentTimeMillis();
}
} else if (keyCode == KeyEvent.KEYCODE_BACK && action == KeyEvent.ACTION_UP) {
mBackKeyAction = KeyEvent.ACTION_UP; //记录松下状态
mActionTime = 0;
}

//长按,且Back键和音量变大键没松
if (isLongPress() && mBackKeyAction == KeyEvent.ACTION_DOWN && mVolumnUpKeyAction == KeyEvent.ACTION_DOWN) {
//do something
Toast.makeText(MainActivity.this, "TestTest", Toast.LENGTH_SHORT).show();
//事件不下发啦
return true;
}

return super.dispatchKeyEvent(event);
}

private boolean isLongPress() {
if (System.currentTimeMillis() - mActionTime > 2000) {
return true;
} else {
return false;
}
}