浮窗WindowManager view返回和Home按键事件监听
出于功能需求,需要在所有的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
1
2
3
4
5
6
7
8
9
|
<?xml version=“1.0” encoding=”utf-8″?>
<YOUR.PACKAGE.NAME.FloatingWindowView
xmlns:android=“http://schemas.android.com/apk/res/android”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:orientation=“vertical”
android:weightSum=“1”>
</YOUR.PACKAGE.NAME.FloatingWindowView>
|
下面附赠哪都能搜索的到的WidnowManager Home按键监听。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
private IntentFilter mHomeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
private BroadcastReceiver mHomeListenerReceiver = new BroadcastReceiver() {
final String SYSTEM_DIALOG_REASON_KEY = “reason”;
final String SYSTEM_DIALOG_REASON_HOME_KEY = “homekey”;
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)
&& reason != null && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
closeFloatingWindow();
}
}
};
|
打开浮窗时调用:
1
|
this.registerReceiver(mHomeListenerReceiver, mHomeFilter);
|
关闭浮窗时调用:
1
|
this.unregisterReceiver(mHomeListenerReceiver);
|