1. 在Manifest中添加权限
<!--悬浮窗权限-->
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
2. 在代码中判断权限,并添加
private void startFloatingService() {
if (Settings.canDrawOverlays(this)) {
Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "请授权", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 0){
if (Settings.canDrawOverlays(this)) {
Toast.makeText(this, "授权成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "请授权", Toast.LENGTH_SHORT).show();
startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), 0);
}
}
}
3. 调用
@Override
protected void initView() {
startFloatingService();
final WindowManager mWm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
final Button view = new Button(this);
view.setAllCaps(false);
view.setText("我是悬浮窗啊!");
final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();
mParams.width = 800;
mParams.height = 800;
mParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
mParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;
mParams.format = PixelFormat.RGBA_8888;
mWm.addView(view, mParams);
view.setOnTouchListener(new View.OnTouchListener() {
private int x;
private int y;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x = (int) event.getRawX();
y = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int moveX = (int) event.getRawX();
int moveY = (int) event.getRawY();
int diffX = moveX - x;
int diffY = moveY - y;
mParams.x = mParams.x + diffX;
mParams.y = mParams.y + diffY;
x = moveX;
y = moveY;
mWm.updateViewLayout(view, mParams);
break;
}
return false;
}
});
}
参考1
参考2
参考3