你好,游客 登录 注册 搜索
背景:
阅读新闻

Android中按键消息的派发过程及源码分析

[日期:2012-07-02] 来源:Linux社区  作者:zjmdp [字体:大 中 小]

下面来具体看下Activity中dispatchKeyEvent的执行过程,首先来看源码:

  1. public boolean dispatchKeyEvent(KeyEvent event) {  
  2.     onUserInteraction();  
  3.     Window win = getWindow();  
  4.     if (win.superDispatchKeyEvent(event)) {  
  5.         return true;  
  6.     }  
  7.     View decor = mDecor;  
  8.     if (decor == null) decor = win.getDecorView();  
  9.     return event.dispatch(this, decor != null  
  10.             ? decor.getKeyDispatcherState() : null, this);  
  11. }  

主要过程如下:

1、调用onUserInteraction(),可重载该函数在消息派发前做一些处理

2、回调Activity包含的Window对象的superDispatchKeyEvent,该函数继而调用mDecor.superDispatchKveyEent,该函数继而又调用super.dispatchKeyEvent,DecorView的父类是FrameLayout,而FrameLayout未重载dispatchKeyEvent,因此最终调用ViewGroup的dispatchKeyEvent

3、如果DecorView未消耗消息,则调用event的dispatch()函数,这里的第一个参数receiver是Activity对象

  1. @Override  
  2.     public boolean superDispatchKeyEvent(KeyEvent event) {  
  3.         return mDecor.superDispatchKeyEvent(event);  
  4.     }  

 

  1.  public boolean superDispatchKeyEvent(KeyEvent event) {  
  2.     if (super.dispatchKeyEvent(event)) {  
  3.         return true;  
  4.     }  
  5.   
  6.     // Not handled by the view hierarchy, does the action bar want it   
  7.     // to cancel out of something special?   
  8.     if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {  
  9.         final int action = event.getAction();  
  10.         // Back cancels action modes first.   
  11.         if (mActionMode != null) {  
  12.             if (action == KeyEvent.ACTION_UP) {  
  13.                 mActionMode.finish();  
  14.             }  
  15.             return true;  
  16.         }  
  17.   
  18.         // Next collapse any expanded action views.   
  19.         if (mActionBar != null && mActionBar.hasExpandedActionView()) {  
  20.             if (action == KeyEvent.ACTION_UP) {  
  21.                 mActionBar.collapseActionView();  
  22.             }  
  23.             return true;  
  24.         }  
  25.     }  
  26.   
  27.     return false;  
  28. }  
linux
相关资讯       Android开发入门 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款