浮窗WindowManager view返回和Home按键事件监听

出于功能需求,须要在全部的view之上显示浮窗,因而须要在WindowManager的View上处理返回键的响应,android

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,死都收不到返回键的事件的!web

 

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.xmlide

下面附赠哪都能搜索的到的WidnowManager Home按键监听。this

打开浮窗时调用:spa

关闭浮窗时调用:code

相关文章
相关标签/搜索