下面来具体看下Activity中dispatchKeyEvent的执行过程,首先来看源码:
- public boolean dispatchKeyEvent(KeyEvent event) {
- onUserInteraction();
- Window win = getWindow();
- if (win.superDispatchKeyEvent(event)) {
- return true;
- }
- View decor = mDecor;
- if (decor == null) decor = win.getDecorView();
- return event.dispatch(this, decor != null
- ? decor.getKeyDispatcherState() : null, this);
- }
主要过程如下:
1、调用onUserInteraction(),可重载该函数在消息派发前做一些处理
2、回调Activity包含的Window对象的superDispatchKeyEvent,该函数继而调用mDecor.superDispatchKveyEent,该函数继而又调用super.dispatchKeyEvent,DecorView的父类是FrameLayout,而FrameLayout未重载dispatchKeyEvent,因此最终调用ViewGroup的dispatchKeyEvent
3、如果DecorView未消耗消息,则调用event的dispatch()函数,这里的第一个参数receiver是Activity对象
- @Override
- public boolean superDispatchKeyEvent(KeyEvent event) {
- return mDecor.superDispatchKeyEvent(event);
- }
- public boolean superDispatchKeyEvent(KeyEvent event) {
- if (super.dispatchKeyEvent(event)) {
- return true;
- }
- // Not handled by the view hierarchy, does the action bar want it
- // to cancel out of something special?
- if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
- final int action = event.getAction();
- // Back cancels action modes first.
- if (mActionMode != null) {
- if (action == KeyEvent.ACTION_UP) {
- mActionMode.finish();
- }
- return true;
- }
- // Next collapse any expanded action views.
- if (mActionBar != null && mActionBar.hasExpandedActionView()) {
- if (action == KeyEvent.ACTION_UP) {
- mActionBar.collapseActionView();
- }
- return true;
- }
- }
- return false;
- }
