蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线 WindowManager DisplayMetrics、窗口标志与 API 26+ 悬浮窗拖动状态机核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-windowmanager.py
explore-tutorial-windowmanager.py205 行
"""Offline Android system-service verifier for Ch 142: WindowManager."""
from dataclasses import dataclass
import json
import xml.etree.ElementTree as ET


VERSION = (
    "CPython 3.12.14 offline Android system-service/sensor/capstone verifier "
    "(Android SDK/emulator absent)"
)

FLAG_FULLSCREEN = 0x00000400
FLAG_KEEP_SCREEN_ON = 0x00000080
FLAG_NOT_FOCUSABLE = 0x00000008
FLAG_NOT_TOUCH_MODAL = 0x00000020

TYPE_SYSTEM_ALERT = 2003
TYPE_APPLICATION_OVERLAY = 2038


@dataclass
class DisplayMetrics:
    width_pixels: int
    height_pixels: int
    density: float

    def width_dp(self) -> float:
        return round(self.width_pixels / self.density, 2)

    def height_dp(self) -> float:
        return round(self.height_pixels / self.density, 2)


@dataclass
class WindowLayoutParams:
    type: int
    flags: int
    width: int
    height: int
    x: int
    y: int
    format: str = "RGBA_8888"
    gravity: str = "LEFT"


def select_overlay_window_type(api_level: int) -> int:
    return TYPE_APPLICATION_OVERLAY if api_level >= 26 else TYPE_SYSTEM_ALERT


def main() -> None:
    # Case 1: DisplayMetrics screen dimensions (API <17 Display vs DisplayMetrics vs API 30+ WindowMetrics)
    dm = DisplayMetrics(width_pixels=1080, height_pixels=1920, density=3.0)
    hw = [dm.width_pixels, dm.height_pixels]
    c1_actual = {
        "screen_hw_px": hw,
        "screen_w_px": hw[0],
        "screen_h_px": hw[1],
        "screen_dp": [dm.width_dp(), dm.height_dp()],
        "toast_text": f"当前手机的屏幕宽高:{dm.width_pixels}*{dm.height_pixels}",
    }
    c1_expected = {
        "screen_hw_px": [1080, 1920],
        "screen_w_px": 1080,
        "screen_h_px": 1920,
        "screen_dp": [360.0, 640.0],
        "toast_text": "当前手机的屏幕宽高:1080*1920",
    }

    # Case 2: Window flags (FLAG_FULLSCREEN + FLAG_KEEP_SCREEN_ON add/clear)
    window_flags = 0
    window_flags |= FLAG_FULLSCREEN
    fullscreen_set = bool(window_flags & FLAG_FULLSCREEN)
    window_flags |= FLAG_KEEP_SCREEN_ON
    keep_on_enabled = bool(window_flags & FLAG_KEEP_SCREEN_ON)
    window_flags &= ~FLAG_KEEP_SCREEN_ON
    keep_on_cleared = bool(window_flags & FLAG_KEEP_SCREEN_ON)
    fullscreen_still_set = bool(window_flags & FLAG_FULLSCREEN)

    c2_actual = {
        "fullscreen_set": fullscreen_set,
        "keep_screen_on_enabled": keep_on_enabled,
        "keep_screen_on_after_clear": keep_on_cleared,
        "fullscreen_preserved": fullscreen_still_set,
    }
    c2_expected = {
        "fullscreen_set": True,
        "keep_screen_on_enabled": True,
        "keep_screen_on_after_clear": False,
        "fullscreen_preserved": True,
    }

    # Case 3: Floating overlay LayoutParams, API 26+ TYPE_APPLICATION_OVERLAY, drag delta update
    params = WindowLayoutParams(
        type=select_overlay_window_type(26),
        flags=FLAG_NOT_TOUCH_MODAL | FLAG_NOT_FOCUSABLE,
        width=200,
        height=200,
        x=200,
        y=0,
    )
    # Simulate ACTION_DOWN at raw (250, 100), ACTION_MOVE to (370, 260)
    last_x, last_y = 250, 100
    param_x, param_y = params.x, params.y
    dx, dy = 370 - last_x, 260 - last_y
    params.x = param_x + dx
    params.y = param_y + dy

    # Simulate launcher/app visibility state machine
    home_packages = {"com.android.launcher3", "com.google.android.apps.nexuslauncher"}
    is_added = True
    transitions = []
    for top_pkg in ("com.android.launcher3", "com.example.browser", "com.android.launcher3"):
        in_home = top_pkg in home_packages
        if in_home and not is_added:
            is_added = True
            transitions.append(("addView", top_pkg))
        elif not in_home and is_added:
            is_added = False
            transitions.append(("removeView", top_pkg))
        else:
            transitions.append(("noop", top_pkg))

    c3_actual = {
        "legacy_api23_type": select_overlay_window_type(23),
        "modern_api26_type": select_overlay_window_type(26),
        "dragged_xy": [params.x, params.y],
        "allows_outside_touch": bool(params.flags & FLAG_NOT_TOUCH_MODAL),
        "non_focusable": bool(params.flags & FLAG_NOT_FOCUSABLE),
        "launcher_transitions": transitions,
    }
    c3_expected = {
        "legacy_api23_type": 2003,
        "modern_api26_type": 2038,
        "dragged_xy": [320, 160],
        "allows_outside_touch": True,
        "non_focusable": True,
        "launcher_transitions": [
            ("noop", "com.android.launcher3"),
            ("removeView", "com.example.browser"),
            ("addView", "com.android.launcher3"),
        ],
    }

    # Case 4: Manifest overlay permission & service registration
    manifest = """<manifest xmlns:android="http://schemas.android.com/apk/res/android">
        <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
        <uses-permission android:name="android.permission.GET_TASKS" />
        <application>
            <service android:name=".MainService" />
        </application>
    </manifest>"""
    root = ET.fromstring(manifest)
    ns = "{http://schemas.android.com/apk/res/android}"
    perms = [e.attrib[f"{ns}name"] for e in root.findall("uses-permission")]
    services = [e.attrib[f"{ns}name"] for e in root.findall("./application/service")]
    c4_actual = {
        "permissions": perms,
        "services": services,
        "get_tasks_deprecated_api": 21,
    }
    c4_expected = {
        "permissions": [
            "android.permission.SYSTEM_ALERT_WINDOW",
            "android.permission.GET_TASKS",
        ],
        "services": [".MainService"],
        "get_tasks_deprecated_api": 21,
    }

    cases = [
        {
            "name": "windowmanager_displaymetrics_dimensions",
            "summary": "验证 WindowManager + DisplayMetrics 屏幕像素宽高及 dp 换算",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "window_flags_fullscreen_and_keep_screen_on",
            "summary": "验证 FLAG_FULLSCREEN 与 FLAG_KEEP_SCREEN_ON 位标志设置与独立清除互不干扰",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "floating_overlay_type_drag_and_visibility",
            "summary": "验证悬浮窗 API 26+ TYPE_APPLICATION_OVERLAY 迁移、拖动偏移更新与桌面切换显隐状态机",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
        {
            "name": "overlay_manifest_permissions_and_service",
            "summary": "验证悬浮窗清单权限 SYSTEM_ALERT_WINDOW/GET_TASKS 与 MainService 注册结构",
            "expected": c4_expected,
            "actual": c4_actual,
            "passed": c4_actual == c4_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/android-tutorial-windowmanager-lab/explore-tutorial-windowmanager.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-tutorial-windowmanager.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Android

课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip

下载课程关联工程包:Android

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1979.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习