"""Offline Android verifier for Ch47: Toast queue, duration normalization & API 30+ compatibility."""
import json
import xml.etree.ElementTree as ET
from dataclasses import dataclass
ANDROID_NS = "{http://schemas.android.com/apk/res/android}"
LENGTH_SHORT = 0
LENGTH_LONG = 1
SHORT_DELAY_MS = 2000
LONG_DELAY_MS = 3500
def normalize_toast_duration_ms(duration_flag: int) -> int:
# Android NotificationManagerService normalizes non-LONG values to SHORT
return LONG_DELAY_MS if duration_flag == LENGTH_LONG else SHORT_DELAY_MS
@dataclass
class ToastRecord:
text: str
duration_ms: int
gravity: str
custom_view: bool
foreground: bool
class MockToastQueue:
def __init__(self, target_api: int):
self.target_api = target_api
self.queue: list[ToastRecord] = []
def enqueue(self, rec: ToastRecord) -> dict:
if self.target_api >= 30 and rec.custom_view and not rec.foreground:
return {"enqueued": False, "reason": "background_custom_toast_blocked_api30"}
effective_gravity = "default_bottom" if (self.target_api >= 30 and not rec.custom_view) else rec.gravity
self.queue.append(rec)
return {"enqueued": True, "effective_gravity": effective_gravity, "duration_ms": rec.duration_ms}
def drain_schedule(self) -> list[dict]:
t = 0
timeline = []
for rec in self.queue:
timeline.append({"text": rec.text, "start_ms": t, "end_ms": t + rec.duration_ms})
t += rec.duration_ms
self.queue.clear()
return timeline
def main() -> None:
# Case 1: Duration normalization & FIFO Toast queue timeline
q28 = MockToastQueue(target_api=28)
q28.enqueue(ToastRecord("提示A", normalize_toast_duration_ms(LENGTH_SHORT), "CENTER", False, True))
q28.enqueue(ToastRecord("提示B", normalize_toast_duration_ms(LENGTH_LONG), "BOTTOM", False, True))
q28.enqueue(ToastRecord("任意值9999", normalize_toast_duration_ms(9999), "BOTTOM", False, True))
timeline = q28.drain_schedule()
act1 = {
"short_ms": normalize_toast_duration_ms(LENGTH_SHORT),
"long_ms": normalize_toast_duration_ms(LENGTH_LONG),
"arbitrary_9999_ms": normalize_toast_duration_ms(9999),
"timeline": timeline,
}
exp1 = {
"short_ms": 2000,
"long_ms": 3500,
"arbitrary_9999_ms": 2000,
"timeline": [
{"text": "提示A", "start_ms": 0, "end_ms": 2000},
{"text": "提示B", "start_ms": 2000, "end_ms": 5500},
{"text": "任意值9999", "start_ms": 5500, "end_ms": 7500},
],
}
# Case 2: Legacy Toast view mutation (image prepend + message color)
children = [{"id": "android.R.id.message", "text": "带图吐司", "color": "WHITE"}]
children.insert(0, {"id": "ImageView", "src": "mipmap/ic_icon_qitao"})
children[1]["color"] = "YELLOW"
act2 = {"child_order": [c["id"] for c in children], "msg_color": children[1]["color"]}
exp2 = {"child_order": ["ImageView", "android.R.id.message"], "msg_color": "YELLOW"}
# Case 3: Custom Toast shape drawable & layout XML parsing
shape_xml = """
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#BADB66" />
<stroke android:width="1px" android:color="#FFFFFF" />
<corners android:bottomLeftRadius="50px" android:topRightRadius="50px" />
<padding android:left="5dp" android:top="5dp" android:right="5dp" android:bottom="5dp" />
</shape>
"""
layout_xml = """
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lly_toast" android:background="@drawable/bg_toast" android:orientation="horizontal">
<ImageView android:id="@+id/img_logo" android:layout_width="24dp" android:layout_height="24dp" />
<TextView android:id="@+id/tv_msg" android:textSize="20sp" />
</LinearLayout>
"""
s_root = ET.fromstring(shape_xml)
l_root = ET.fromstring(layout_xml)
act3 = {
"solid_color": s_root.find("solid").attrib[ANDROID_NS + "color"],
"corner_radius": s_root.find("corners").attrib[ANDROID_NS + "bottomLeftRadius"],
"layout_bg": l_root.attrib[ANDROID_NS + "background"],
"msg_size": l_root.find("TextView").attrib[ANDROID_NS + "textSize"],
}
exp3 = {
"solid_color": "#BADB66",
"corner_radius": "50px",
"layout_bg": "@drawable/bg_toast",
"msg_size": "20sp",
}
# Case 4: Android 11 (API 30+) Toast compatibility constraints
q30 = MockToastQueue(target_api=30)
r_text = q30.enqueue(ToastRecord("文本吐司", SHORT_DELAY_MS, "CENTER", False, True))
r_bg_custom = q30.enqueue(ToastRecord("后台自定义", LONG_DELAY_MS, "CENTER", True, False))
r_fg_custom = q30.enqueue(ToastRecord("前台自定义", LONG_DELAY_MS, "CENTER", True, True))
act4 = {"text_toast_api30": r_text, "bg_custom_api30": r_bg_custom, "fg_custom_api30": r_fg_custom}
exp4 = {
"text_toast_api30": {"enqueued": True, "effective_gravity": "default_bottom", "duration_ms": 2000},
"bg_custom_api30": {"enqueued": False, "reason": "background_custom_toast_blocked_api30"},
"fg_custom_api30": {"enqueued": True, "effective_gravity": "CENTER", "duration_ms": 3500},
}
cases = [
{
"name": "toast_queue_and_duration_normalization",
"summary": "验证 Toast FIFO 排队时序及非 LENGTH_LONG 参数统一归一为 SHORT(2000ms)",
"expected": exp1,
"actual": act1,
"passed": act1 == exp1,
},
{
"name": "legacy_toast_view_image_injection",
"summary": "验证传统 getView() 在索引 0 插入 ImageView 并修改 android.R.id.message 颜色",
"expected": exp2,
"actual": act2,
"passed": act2 == exp2,
},
{
"name": "custom_toast_shape_and_layout_xml",
"summary": "解析圆角背景 shape 与自定义吐司布局 XML 的颜色、圆角与字号属性",
"expected": exp3,
"actual": act3,
"passed": act3 == exp3,
},
{
"name": "api30_custom_toast_policy_guard",
"summary": "验证 Android 11(API 30+) 屏蔽后台自定义 Toast 且文本 Toast 忽略 setGravity 的兼容行为",
"expected": exp4,
"actual": act4,
"passed": act4 == exp4,
},
]
print(
json.dumps(
{
"version": "CPython 3.12.14 offline Android UI/Event/Handler verifier (Android SDK/emulator absent)",
"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-toast-lab/explore-tutorial-toast.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-tutorial-toast.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联156章) · 含当前章节或实例 · mbskycom202612a1829.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1959.zip