怎么实现android 全局悬浮窗

要实现 Android 全局悬浮窗,可以按照以下步骤:

  1. 在 AndroidManifest.xml 文件中添加 SYSTEM_ALERT_WINDOW 权限:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
  1. 创建一个 Service 类,并在其中创建一个 WindowManager 来管理悬浮窗:
public class FloatingWindowService extends Service {
    
    

    private WindowManager mWindowManager;
    private View mFloatingView;

    @Override
    public void onCreate() {
    
    
        super.onCreate();

        // 初始化 WindowManager
        mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        // 创建悬浮窗 View
        mFloatingView = LayoutInflater.from(this).inflate(R.layout.floating_window, null);

        // 设置悬浮窗 View 的参数
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ?
                        WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY :
                        WindowManager.LayoutParams.TYPE_PHONE,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);

        // 添加悬浮窗 View
        mWindowManager.addView(mFloatingView, params);
    }

    @Override
    public void onDestroy() {
    
    
        super.onDestroy();

        // 移除悬浮窗 View
        if (mFloatingView != null) {
    
    
            mWindowManager.removeView(mFloatingView);
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
    
    
        return null;
    }
}
  1. 在悬浮窗 View 的布局文件中添加需要展示的内容:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <!-- 添加需要展示的内容 -->

</RelativeLayout>
  1. 在 Activity 中启动 Service:
Intent intent = new Intent(this, FloatingWindowService.class);
startService(intent);
  1. 最后,记得在不需要展示悬浮窗时,调用 stopService() 方法停止 Service:
Intent intent = new Intent(this, FloatingWindowService.class);
stopService(intent);

猜你喜欢

转载自blog.csdn.net/yanwenyuan0304/article/details/130077757