出于功能需求,需要在所有的view之上显示浮窗,于是需要在WindowManager的View上处理返回键的响应,
mFloatingWindowView = layoutInflater.inflate(R.layout.floating_window, null, false); mFloatingWindowLayoutParams = new WindowManager.LayoutParams();
// 设置window type
mUserConversationWindowParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
mUserConversationWindowParams.format = PixelFormat.TRANSLUCENT;// 设置图片格式,效果为背景透明
// 设置Window flag
mUserConversationWindowParams.flags =
//可使用FLAG_DISMISS_KEYGUARD选项直接解除非加锁的锁屏状态。此选项只用于最顶层的全屏幕窗口。
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL //必须 设置窗口不拦截窗口范围之外事件
|WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH // 必须 设置在有FLAG_NOT_TOUCH_MODAL属性时,窗口之外事件发生时自己也获取事件
| WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
mWindowManager.addView(mFloatingWindowView, mFloatingWindowLayoutParams);
这里千万要注意不能用WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,我就是死在这上面的,如果设置成FLAG_NOT_FOCUSABLE,死都收不到返回键的事件的!
import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.widget.LinearLayout; /** * Created by KB-Shirlman on 4/26/2016. */ public class FloatingWindowView extends LinearLayout { public FloatingWindowView(Context context) { super(context); } public FloatingWindowView(Context context, AttributeSet attrs) { super(context, attrs); } public FloatingWindowView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK || event.getKeyCode() == KeyEvent.KEYCODE_SETTINGS) {
if(event.getAction()==KeyEvent.ACTION_DOWN){ //按键 按下和移开会有两个不同的事件所以需要区分
closecao(); //点击返回 要执行的方法
}
} return super.dispatchKeyEvent(event); } }
floating_window.xml
下面附赠哪都能搜索的到的WidnowManager Home按键监听。
打开浮窗时调用:
关闭浮窗时调用: