我的应用程序中有以下代码。只要按下音量按钮,我就会得到ACTION_DOWN,但是当我释放它时,我希望得到ACTION_UP。这不会发生。为什么?这可能是我的LG G2(Lollipop)上的一个错误吗?我需要的是为VolumeUp按钮操作添加一个监听器。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
if (event.getAction() == KeyEvent.ACTION_UP) {
//TODO
Log.d(TAG,"VOL UP");
return true;
}
if (event.getAction() == KeyEvent.ACTION_DOWN) {
//TODO
Log.d(TAG,"VOL DOWN");
return true;
}
Log.d(TAG,String.valueOf(keyCode));
return true;
}
return super.onKeyDown(keyCode, event);
}
答案 0 :(得分:0)
这里我编辑两个代码可能是你的工作之一:
代码1:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
changeColor(keyCode);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN ||
keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
// do nothing
return true;
}
return super.onKeyUp(keyCode, event);
}
代码2:
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
return true;
} else if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN) {
return true;
}
return dispatchKeyEvent(event);
}
答案 1 :(得分:0)
您应该尝试捕获所有操作。
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) {
//TODO
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}