我在一个非常简单的活动中实现了onKeyDown和onKeyUp,并注意到Volume Down键的奇怪行为。
以下是代码:
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN))
{
B9=true;
Log.w("Alon", "Volume_down Down "+SystemClock.elapsedRealtime());
}
else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP))
{
B10=true;
Log.w("Alon", "Volume_up Down "+SystemClock.elapsedRealtime());
}
else
return super.onKeyDown(keyCode, event);
return true;
}
public boolean onKeyUp (int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN))
{
B9=false;
Log.w("Alon", "Volume_down Up "+SystemClock.elapsedRealtime());
}
else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP))
{
B10=false;
Log.w("Alon", "Volume_up Up "+SystemClock.elapsedRealtime());
}
else
return super.onKeyDown(keyCode, event);
return true;
}
单击音量调高并尽可能快地放开可以产生正确的结果:
12-15 17:43:22.215: W/Alon(751): Volume_up Down 74650325
12-15 17:43:22.265: W/Alon(751): Volume_up Up 74650374
12-15 17:43:22.705: W/Alon(751): Volume_up Down 74650818
12-15 17:43:22.765: W/Alon(751): Volume_up Up 74650878
12-15 17:43:23.566: W/Alon(751): Volume_up Down 74651675
12-15 17:43:23.656: W/Alon(751): Volume_up Up 74651768
12-15 17:43:24.107: W/Alon(751): Volume_up Down 74652222
12-15 17:43:24.177: W/Alon(751): Volume_up Up 74652284
对降低音量执行相同操作不会:
12-15 17:44:13.139: W/Alon(751): Volume_down Down 74701252
12-15 17:44:13.139: W/Alon(751): Volume_down Up 74701253
12-15 17:44:13.840: W/Alon(751): Volume_down Down 74701950
12-15 17:44:13.840: W/Alon(751): Volume_down Up 74701950
12-15 17:44:14.751: W/Alon(751): Volume_down Down 74702863
12-15 17:44:14.761: W/Alon(751): Volume_down Up 74702865
12-15 17:44:15.431: W/Alon(751): Volume_down Down 74703546
12-15 17:44:15.431: W/Alon(751): Volume_down Up 74703547
12-15 17:44:16.673: W/Alon(751): Volume_down Down 74704785
12-15 17:44:16.673: W/Alon(751): Volume_down Up 74704785
我在两部手机上测试并得到了相同的结果 - Nexus 4和Galaxy S.这是Android中的一个已知问题吗?我做错了吗?
答案 0 :(得分:1)
VOLUME_DOWN + POWER_KEY是触发屏幕截图的特殊组合键。
当VOLUME_DOWN键发生故障时,事件将在PhoneWindowManager
发送之前被截获。
PhoneWindowManager
告诉调度员在调度前等待一段时间(150毫秒),以防用户触发屏幕截图......以及调度员所做的事情:他等待。 ..
...然后VOLUME_DOWN键上升。调度员可以立即调度VOLUME_DOWN up事件(即在这种情况下:PhoneWindowManager没有任何理由告诉调度员等待)。
但是:队列中有待处理的VOLUME_DOWN。因此,调度员在VOLUME_DOWN之后立即向下调度VOLUME_DOWN。
PhoneWindowManager
的一些代码:
// If we think we might have a volume down & power key chord on the way
// but we're not sure, then tell the dispatcher to wait a little while and
// try again later before dispatching.
if (mScreenshotChordEnabled && (flags & KeyEvent.FLAG_FALLBACK) == 0) {
if (mVolumeDownKeyTriggered && !mPowerKeyTriggered) {
final long now = SystemClock.uptimeMillis();
final long timeoutTime = mVolumeDownKeyTime + SCREENSHOT_CHORD_DEBOUNCE_DELAY_MILLIS;
if (now < timeoutTime) {
return timeoutTime - now;
}
}
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
&& mVolumeDownKeyConsumedByScreenshotChord) {
if (!down) {
mVolumeDownKeyConsumedByScreenshotChord = false;
}
return -1;
}
}