今天查找了很多资料实现屏蔽android应用中home键、back键的使用,在android4.0之后google由于安全原因将onKeyDown中重写home键事件的方法封住了,使得屏蔽home键的任务非常难实现。
最后终于在github上找到了一个能用的方法!!!!这个方法似乎在锁屏应用中经常被用到。
奉送上地址: https://github.com/shaobin0604/Android-HomeKey-Locker
以下是我分析得出的原理,各位帮忙看看对不对
首先我们构造一个OverlayDialog类,继承自AlertDialog
构造方法:
public OverlayDialog(Activity activity) {
super(activity, R.style.OverlayDialog);
WindowManager.LayoutParams params = getWindow().getAttributes();
params.type = TYPE_SYSTEM_ERROR;
params.dimAmount = 0.0F; // transparent
params.width = 0;
params.height = 0;
params.gravity = Gravity.BOTTOM;
getWindow().setAttributes(params);
getWindow().setFlags(FLAG_SHOW_WHEN_LOCKED | FLAG_NOT_TOUCH_MODAL, 0xffffff);
setOwnerActivity(activity);
setCancelable(false);
}
android API对LayoutParams.Type的说明:
Window type: internal system error windows, appear on top of everything they can. In multiuser systems shows only on the owning user's window.
dimAmount:
When FLAG_DIM_BEHIND
is set, this is the amount of dimming to apply. Range is from 1.0 for completely opaque to 0.0 for no dim.
Push object to the bottom of its container, not changing its size.
FLAG_SHOW_WHEN_LOCKED:
Window flag: special flag to let windows be shown when the screen is locked.
FLAG_NOT_TOUCH_MODAL:
Window flag: even when this window is focusable (its FLAG_NOT_FOCUSABLE
is not set), allow any pointer events outside of the window to be sent to the windows behind it.
setOwernActivity(activity);
Sets the Activity that owns this dialog. An example use: This Dialog will use the suggested volume control stream of the Activity.
实现的原理是构建一个system level的AlertDialog,重点是将params.type改成TYEP_SYSTEM_ERROR,这样的时候会连同屏幕也被屏蔽掉(alertdialog的普通功能就是屏蔽掉屏幕以及back键,升级成system level之后就连同home键一起屏蔽了),我们通过设置setFlag让屏幕显示并且屏幕的点击事件可以得到响应,这样就使得back、home、menu都被屏蔽了。
(在测试的时候遇到一些问题:1.在一些特殊设备上如我的mx4 pro、samsung tab 13由于不同的framework,有些按钮和功能会无法实现
2.由于实现屏蔽是通过alertdialog完成的,在app中一旦出现新的alertdialog就会替换掉这个system level的alertdialog,从而退出屏蔽)