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