这个技术只要掌握好WindowManager的显示类型即可。只要学会了该知识点,就能够实现例如360,QQ管家那样的悬浮窗效果。下面看看效果图。。。

核心代码:
private boolean isAdded = false; // 是否已增加悬浮窗
private static WindowManager wm;
private static WindowManager.LayoutParams params;
private LinearLayout layout;
private Button btnStart;
private Button btnScreen;
实现函数
/**
* 创建悬浮窗
*/
@SuppressLint("ClickableViewAccessibility")
private void createFloatView() {
btnStart = new Button(getApplicationContext());
btnStart.setText(getString(R.string.string_init));
btnStart.setOnClickListener(this);
btnScreen = new Button(getApplicationContext());
btnScreen.setText(getString(R.string.string_screen));
btnScreen.setOnClickListener(this);
wm = (WindowManager) getApplicationContext().getSystemService(
Context.WINDOW_SERVICE);
params = new WindowManager.LayoutParams();
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
/*
* 如果设置为params.type = WindowManager.LayoutParams.TYPE_PHONE; 那么优先级会降低一些,
* 即拉下通知栏不可见
*/
params.format = PixelFormat.RGBA_8888; // 设置图片格式,效果为背景透明
// 设置Window flag
params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
/*
* 下面的flags属性的效果形同“锁定”。 悬浮窗不可触摸,不接受任何事件,同时不影响后面的事件响应。
* wmParams.flags=LayoutParams.FLAG_NOT_TOUCH_MODAL |
* LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_NOT_TOUCHABLE;
*/
// 设置悬浮窗的长得宽
params.width = -2;
params.height = -2;
// 设置悬浮窗的Touch监听
layout = new LinearLayout(getApplicationContext());
layout.setOrientation(LinearLayout.HORIZONTAL);
layout.setClickable(true);
layout.setPadding(30, 30, 30, 30);
layout.addView(btnStart);
layout.addView(btnScreen);
layout.setOnTouchListener(new OnTouchListener() {
int lastX, lastY;
int paramX, paramY;
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
paramX = params.x;
paramY = params.y;
break;
case MotionEvent.ACTION_MOVE:
int dx = (int) event.getRawX() - lastX;
int dy = (int) event.getRawY() - lastY;
params.x = paramX + dx;
params.y = paramY + dy;
// 更新悬浮窗位置
wm.updateViewLayout(layout, params);
break;
}
return true;
}
});
wm.addView(layout, params);
isAdded = true;
}
还有一个权限是必须要添加的。
本文链接:https://it72.com:4443/6146.htm