You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter运行在Android悬浮窗中时如何获取设备屏幕尺寸?

Flutter Android悬浮窗场景获取完整物理屏幕尺寸的解决方案

悬浮窗场景下MediaQuery被限制为仅返回悬浮窗自身窗口的尺寸,属于Android平台的沙箱隔离特性,可通过以下两种方案解决:

方案1:通过MethodChannel调用原生API实时获取

这是最稳定、适配性最强的方案,支持动态响应屏幕旋转、折叠屏状态变更等场景:

  1. 首先在Android原生层注册MethodChannel通道,实现获取真实物理屏幕尺寸的逻辑,注意要使用getRealMetrics接口,避免拿到扣除系统栏高度的裁剪尺寸:
// Android 端 Kotlin 实现代码
class MainActivity : FlutterActivity() {
    private val CHANNEL = "com.example/screen_utils"

    override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
        super.configureFlutterEngine(flutterEngine)
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
            if (call.method == "getRealScreenSize") {
                val screenSize = getPhysicalScreenSize()
                result.success(screenSize)
            } else {
                result.notImplemented()
            }
        }
    }

    private fun getPhysicalScreenSize(): Map<String, Double> {
        val windowManager = getSystemService(WINDOW_SERVICE) as WindowManager
        val displayMetrics = DisplayMetrics()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            display?.getRealMetrics(displayMetrics)
        } else {
            @Suppress("DEPRECATION")
            windowManager.defaultDisplay.getRealMetrics(displayMetrics)
        }
        // 返回dp单位的尺寸,如果需要像素可以直接返回widthPixels/heightPixels
        val density = displayMetrics.density
        return mapOf(
            "width" to displayMetrics.widthPixels / density,
            "height" to displayMetrics.heightPixels / density
        )
    }
}
  1. Flutter侧通过通道调用原生方法获取尺寸即可:
// Flutter 端调用代码
import 'package:flutter/services.dart';
import 'dart:ui';

class ScreenUtils {
  static const MethodChannel _channel = MethodChannel("com.example/screen_utils");

  static Future<Size> getRealScreenSize() async {
    final Map<String, double> result = Map.from(
      await _channel.invokeMethod("getRealScreenSize")
    );
    return Size(result["width"]!, result["height"]!);
  }
}

方案2:提前缓存屏幕尺寸

如果你的应用不需要适配屏幕旋转、折叠屏切换等动态变更场景,可以用更简单的缓存方案:

  • 应用首次以全屏模式启动时,用MediaQuery.of(context).size拿到真实物理屏幕尺寸,通过shared_preferences等本地存储组件缓存下来
  • 后续悬浮窗场景启动时,直接读取本地缓存的尺寸值即可

注意事项

  • 不要使用原生API的getMetrics接口,该接口会扣除状态栏、导航栏的高度,无法拿到完整物理屏幕尺寸
  • 适配Android 12及以上版本时,无需额外申请权限即可调用上述原生屏幕尺寸获取接口

内容的提问来源于stack exchange,提问作者Long Lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:42:00