使用WindowManager的addView的方法可以在其他应用最上层,甚至手机桌面最上层显示窗口。也就是实现桌面悬浮窗的功能。
根据WindowManager.LayoutParams属性不同,效果也就不同。比如我们设置的属性如下
mWindowManager = (WindowManager) context.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
mParams = new WindowManager.LayoutParams();
mParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
mParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
mParams.width = -2;
mParams.height = -2;
mParams.format = PixelFormat.RGBA_8888;
mParams.gravity = gravity;
width = -2 和 height = -2 表示 width = WindowManager.LayoutParams.WRAP_CONTENT 来设置属性。
在此重点说明一下LayoutParams的flags属性:两个比较常用的属性
FLAG_NOT_TOUCH_MODAL:Even when this window is focusable (its {@link #FLAG_NOT_FOCUSABLE is not set),
allow any pointer events outside of the window to be sent to the windows behind it.
即使在该window在可获得焦点情况下,仍然把该window之外的任何event发送到该window之后的其他window。
FLAG_NOT_FOCUSABLE:this window won't ever get key input focus, so the user can not send key or other button events to it.
让window不能获得焦点,这样用户快就不能向该window发送按键事,即屏蔽掉onKey事件。
我在程序中使用FLAG_NOT_TOUCH_MODAL 标志来创建的view,表面上一切正常,发现一个有个bug就是“菜单键”和“返回键”失效了,
在其他程序中使用返回键和菜单键均没有任何反应,个别手机上“home”键也会出现问题。调试时发现该view能收到OnKeyDown和OnKeyUp事件,
即使在OnKeyDown和OnKeyUp事件中返回false,其他程序也无法接收到OnKeyDown和OnKeyUp事件。
修改为mParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;后,
一切正常,返回键和菜单键能够收到对应的OnKey事件。