android 捕获并处理HOME键

来源:互联网 发布:气质干净的男生知乎 编辑:程序博客网 时间:2024/05/21 07:02

第一部分是解决2.2或者之前系统版本home的监听,第二部分是4.0.x的home监听

第一种方式:android 对home键的监听,加上了权限,必须取得对处理home键事件的权限,才能对home键进行操作,

只对2.2及以前的系统有效。

     1,加上权限

      <uses-permission android:name="android.permission.DISABLE_KEYGUARD"/>

     就是让键盘守卫失去能了,根据英文大体是这个意思

    2,重载以下两个方法

@Override public boolean onKeyDown(int keyCode, KeyEvent event) {    if(KeyEvent.KEYCODE_HOME==keyCode){       //写要执行的动作或者任务         android.os.Process.killProcess(android.os.Process.myPid());  }  return super.onKeyDown(keyCode, event); }   @Override    public void onAttachedToWindow(){       this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);       super.onAttachedToWindow();    }

第二种方法

 1. 在activity中加上这段代码就可以屏蔽home键(onKeyDown事件会捕捉到home键)。 

 public void onAttachedToWindow()       {                this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);                   super.onAttachedToWindow();         }   
2.因为android系统自己对与home键power键在PhoneWindowManager中做了处理,不会返回到上层应用的。以下为系统源码: 
    \frameworks\policies\base\phone\com\android\internal\policy\impl\PhoneWindowManager.java 1089行

   if (code == KeyEvent.KEYCODE_HOME) {                           // If a system window has focus, then it doesn't make sense                    // right now to interact with applications.                    WindowManager.LayoutParams attrs = win != null ? win.getAttrs() : null;                   if (attrs != null) {                       final int type = attrs.type;                       if (type == WindowManager.LayoutParams.TYPE_KEYGUARD                               || type == WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG) {                           // the "app" is keyguard, so give it the key                            return false;                       }                       final int typeCount = WINDOW_TYPES_WHERE_HOME_DOESNT_WORK.length;                       for (int i=0; i<typeCount; i++) {                           if (type == WINDOW_TYPES_WHERE_HOME_DOESNT_WORK[i]) {                               // don't do anything, but also don't pass it to the app                                return true;                           }                       }                   }   

    type == WindowManager.LayoutParams.TYPE_KEYGUARD这一句,我们可以看到,android对于锁屏特殊判断了,所以我就模拟这个进行的实现,只是有一点,activity中重写onAttachedToWindow()方法需要api 5以上。 

监听玩后,取消了回到桌面的效果,可以回到桌面

Intent i = new Intent(Intent.ACTION_MAIN);
  i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  i.addCategory(Intent.CATEGORY_HOME);
  startActivity(i);

原创粉丝点击