1 rewrite onattachedtowindow
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
2 rewrite 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 source code
Because the Android system processes the Home Key in phonewindowmanager, it does not return to the upper-layer application. View Source Code:
\ Frameworks \ Policies \ base \ phone \ com \ Android \ internal \ Policy \ impl \ phonewindowmanager. Java row 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
If dialog is displayed in the activity, the preceding two methods cannot be blocked in the activity.
In fact, the principle is the same, but the place is different.
Final dialog = new dialog (this );
Dialog. setcontentview (R. layout. mydailog );
Dialog. Show (); // show should be before settype; otherwise, an error is returned.
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;
}
});
Refer:
Dialog, activity shielding HOME key explanation
Windowmanager. layoutparams