android 屏蔽home键操作

1 重写onAttachedToWindow

public void onAttachedToWindow() {  
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}

 

2 重写onKeyDown

public boolean onKeyDown(int keyCode, KeyEvent event) {  
switch (keyCode) {
case KeyEvent.KeyEvent.KEYCODE_HOME:
Log.i(TAG,"KEYCODE_HOME");
return true;
}
return super.onKeyDown(keyCode, event);
}



3 android源码 

因为android系统自己对home键在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;
}
}
}

 

4 Dialog

如果在Activity弹出dialog,在Activity设置以上2个方法是没办法屏蔽的。 
其实,原理是一样的,只是地方不一样而已。 

final Dialog dialog = new Dialog(this);  
dialog.setContentView(R.layout.mydailog);
dialog.show(); //show应在setType之前,否则报错
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);

dialog.setOnKeyListener(new android.content.DialogInterface.OnKeyListener(){
@Override
public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_HOME:
Log.i(TAG,"KEYCODE_HOME");
return true;
}
return false;
}
});

 

 

参考:

dialog,activity 屏蔽Home键详解

WindowManager.LayoutParams

posted @ 2011-10-28 18:50  因是因非  阅读(1428)  评论(1编辑  收藏  举报