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

运行离线 WallpaperManager 推荐尺寸裁剪、壁纸选择器配置与定时轮播状态核验

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-wallpapermanager.py
explore-tutorial-wallpapermanager.py179 行
"""Offline Android system-service verifier for Ch 144: WallpaperManager."""
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)"
)


@dataclass
class WallpaperManagerModel:
    desired_min_width: int
    desired_min_height: int
    default_wallpaper: str = "system_default_wallpaper"
    current_wallpaper: str | None = None
    live_wallpaper_info: dict | None = None

    def set_resource(self, res_name: str) -> None:
        self.current_wallpaper = res_name
        self.live_wallpaper_info = None

    def clear(self) -> None:
        self.current_wallpaper = None
        self.live_wallpaper_info = None

    def get_drawable(self) -> str:
        return self.current_wallpaper or self.default_wallpaper

    def peek_drawable(self) -> str | None:
        return self.current_wallpaper


def compute_center_crop_rect(src_w: int, src_h: int, dst_w: int, dst_h: int) -> dict[str, int]:
    """Compute centered source crop rectangle matching target wallpaper aspect ratio."""
    src_ratio = src_w / src_h
    dst_ratio = dst_w / dst_h
    if src_ratio > dst_ratio:
        crop_h = src_h
        crop_w = round(src_h * dst_ratio)
    else:
        crop_w = src_w
        crop_h = round(src_w / dst_ratio)
    left = (src_w - crop_w) // 2
    top = (src_h - crop_h) // 2
    return {"left": left, "top": top, "right": left + crop_w, "bottom": top + crop_h}


def main() -> None:
    # Case 1: WallpaperManager desired dimensions, center-crop hint, getDrawable vs peekDrawable
    wm = WallpaperManagerModel(desired_min_width=2160, desired_min_height=1920)
    before_set = {"getDrawable": wm.get_drawable(), "peekDrawable": wm.peek_drawable()}
    wm.set_resource("R.mipmap.gui_1")
    after_set = {"getDrawable": wm.get_drawable(), "peekDrawable": wm.peek_drawable()}
    wm.clear()
    after_clear = {"getDrawable": wm.get_drawable(), "peekDrawable": wm.peek_drawable()}

    # 3840x2160 (16:9) source image cropped to 2160x1920 (9:8 parallax wallpaper)
    crop_parallax = compute_center_crop_rect(3840, 2160, wm.desired_min_width, wm.desired_min_height)
    # 1080x2400 tall image cropped to 1080x1920 (9:16 lockscreen)
    crop_lockscreen = compute_center_crop_rect(1080, 2400, 1080, 1920)

    c1_actual = {
        "desired_dimensions": [wm.desired_min_width, wm.desired_min_height],
        "before_set": before_set,
        "after_set": after_set,
        "after_clear": after_clear,
        "crop_parallax_3840x2160": crop_parallax,
        "crop_lockscreen_1080x2400": crop_lockscreen,
    }
    c1_expected = {
        "desired_dimensions": [2160, 1920],
        "before_set": {"getDrawable": "system_default_wallpaper", "peekDrawable": None},
        "after_set": {"getDrawable": "R.mipmap.gui_1", "peekDrawable": "R.mipmap.gui_1"},
        "after_clear": {"getDrawable": "system_default_wallpaper", "peekDrawable": None},
        "crop_parallax_3840x2160": {"left": 705, "top": 0, "right": 3135, "bottom": 2160},
        "crop_lockscreen_1080x2400": {"left": 0, "top": 240, "right": 1080, "bottom": 2160},
    }

    # Case 2: System wallpaper chooser Intent & Activity wallpaper theme configuration
    manifest = """<manifest xmlns:android="http://schemas.android.com/apk/res/android">
        <uses-permission android:name="android.permission.SET_WALLPAPER" />
        <application>
            <activity android:name=".MainActivity" android:theme="@android:style/Theme.Wallpaper.NoTitleBar" />
            <service android:name=".WallPaperService" />
        </application>
    </manifest>"""
    root = ET.fromstring(manifest)
    ns = "{http://schemas.android.com/apk/res/android}"
    chooser_intent = {
        "action": "android.intent.action.SET_WALLPAPER",
        "chooser_title": "选择壁纸",
    }
    activity_theme = root.find("./application/activity").attrib[f"{ns}theme"]
    perm = root.find("uses-permission").attrib[f"{ns}name"]
    service_name = root.find("./application/service").attrib[f"{ns}name"]
    c2_actual = {
        "chooser_intent": chooser_intent,
        "manifest_theme": activity_theme,
        "permission": perm,
        "service": service_name,
    }
    c2_expected = {
        "chooser_intent": {
            "action": "android.intent.action.SET_WALLPAPER",
            "chooser_title": "选择壁纸",
        },
        "manifest_theme": "@android:style/Theme.Wallpaper.NoTitleBar",
        "permission": "android.permission.SET_WALLPAPER",
        "service": ".WallPaperService",
    }

    # Case 3: Scheduled wallpaper rotation service cycle & button enabled state
    papers = ["R.mipmap.gui_1", "R.mipmap.gui_2", "R.mipmap.gui_3", "R.mipmap.gui_4"]
    current = 0
    applied_sequence = []
    for _ in range(6):
        if current >= len(papers):
            current = 0
        wm.set_resource(papers[current])
        applied_sequence.append(wm.get_drawable())
        current += 1
    btn_on_enabled, btn_off_enabled = True, False
    # Click btn_on
    btn_on_enabled, btn_off_enabled = False, True
    after_start = [btn_on_enabled, btn_off_enabled]
    # Click btn_off
    btn_on_enabled, btn_off_enabled = True, False
    after_stop = [btn_on_enabled, btn_off_enabled]

    c3_actual = {
        "rotation_sequence_6_ticks": applied_sequence,
        "buttons_after_start": after_start,
        "buttons_after_stop": after_stop,
    }
    c3_expected = {
        "rotation_sequence_6_ticks": [
            "R.mipmap.gui_1",
            "R.mipmap.gui_2",
            "R.mipmap.gui_3",
            "R.mipmap.gui_4",
            "R.mipmap.gui_1",
            "R.mipmap.gui_2",
        ],
        "buttons_after_start": [False, True],
        "buttons_after_stop": [True, False],
    }

    cases = [
        {
            "name": "wallpapermanager_dimensions_crop_and_drawables",
            "summary": "验证 WallpaperManager 最小推荐尺寸、居中裁剪矩阵及 getDrawable/peekDrawable/clear 状态差异",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "wallpaper_chooser_theme_and_manifest",
            "summary": "验证 ACTION_SET_WALLPAPER 选择器 Intent、Theme.Wallpaper 主题配置与 SET_WALLPAPER 清单声明",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "scheduled_wallpaper_service_rotation",
            "summary": "验证 AlarmManager + WallPaperService 轮播索引循环及启停按钮状态切换",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_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-wallpapermanager-lab/explore-tutorial-wallpapermanager.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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