事件被派发到View层次结构的根节点DecorView开始分析,这里我们先来看看DecorView#dispatchKeyEvent方法,代码如下:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
final int keyCode = event.getKeyCode();
final int action = event.getAction();
final boolean isDown = action == KeyEvent.ACTION_DOWN;
/// 1. 第一次down事件的时候,处理panel的快捷键
if (isDown && (event.getRepeatCount() == 0)) {
// First handle chording of panel key: if a panel key is held
// but not released, try to execute a shortcut in it.
if ((mPanelChordingKey > 0) && (mPanelChordingKey != keyCode)){
boolean handled = dispatchKeyShortcutEvent(event);
if (handled) { return true; }
}
// If a panel is open, perform a shortcut on it without the
// chorded panel key
if ((mPreparedPanel != null) && mPreparedPanel.isOpen) {
if (performPanelShortcut(mPreparedPanel, keyCode, event, 0)) { returntrue; }
}
}
/// 2. 这里是我们本文的重点,当window没destroy且其Callback非空的话,交给其Callback处理
if (!isDestroyed()) {
// Activity、Dialog都是Callback接口的实现
final Callback cb = getCallback();
// mFeatureId < 0 表示是application的DecorView,比如Activity、Dialog
final boolean handled = cb != null && mFeatureId < 0 ?cb.dispatchKeyEvent(event) // 派发给callback的方法 : super.dispatchKeyEvent(event);