利用WindowManager创建悬浮窗
悬浮窗服务
public class FloatingService extends Service {
private WindowManager windowManager;
private WindowManager.LayoutParams layoutParams;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layoutParams = new WindowManager.LayoutParams();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
}
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
// 设置背景透明
layoutParams.format = PixelFormat.TRANSPARENT;
// layoutParams.format = PixelFormat.RGBA_8888;
layoutParams.windowAnimations = R.style.AnimationTopFade;
layoutParams.gravity = Gravity.CENTER_HORIZONTAL | Gravity.TOP;
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showFloatingWindow();
return super.onStartCommand(intent, flags, startId);
}
private void showFloatingWindow() {
View view = LayoutInflater.from(this).inflate(R.layout.float_view, null);
Button btn = view.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
...
}
});
// show
windowManager.addView(view, layoutParams);
// hide
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
windowManager.removeView(view);
}
}, 4000);
}
}
调用:
@RequiresApi(api = Build.VERSION_CODES.M)
private void showUpdatePwdFloatView() {
// 悬浮窗权限判断
if (!Settings.canDrawOverlays(MainActivity.this)) {
Toast.makeText(this, "为能及时收到通知,建议您开启悬浮窗权限", Toast.LENGTH_LONG).show();
startActivityForResult(new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())), OVERLAYS_CODE);
} else {
startService(new Intent(MainActivity.this, UpdatePwdFloatingService.class));
}
}
记得要在AndroidMainfest.xml里注册服务
<service android:name=".service.FloatingService" />