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

运行 Notification.Builder 生命周期、Android 8+ NotificationChannel 与 PendingIntent 标志离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial-notification.py
explore-tutorial-notification.py226 行
"""Offline Android verifier for Ch48: Notification Builder, PendingIntent flags & NotificationChannel."""
import json
from dataclasses import dataclass, field

DEFAULT_SOUND = 1
DEFAULT_VIBRATE = 2
DEFAULT_LIGHTS = 4
DEFAULT_ALL = DEFAULT_SOUND | DEFAULT_VIBRATE | DEFAULT_LIGHTS

FLAG_ONE_SHOT = 1 << 30
FLAG_NO_CREATE = 1 << 29
FLAG_CANCEL_CURRENT = 1 << 28
FLAG_UPDATE_CURRENT = 1 << 27
FLAG_IMMUTABLE = 1 << 26

PRIORITY_TO_IMPORTANCE = {
    "MAX": ("PRIORITY_MAX", 2, "IMPORTANCE_HIGH"),
    "HIGH": ("PRIORITY_HIGH", 1, "IMPORTANCE_HIGH"),
    "DEFAULT": ("PRIORITY_DEFAULT", 0, "IMPORTANCE_DEFAULT"),
    "LOW": ("PRIORITY_LOW", -1, "IMPORTANCE_LOW"),
    "MIN": ("PRIORITY_MIN", -2, "IMPORTANCE_MIN"),
}


@dataclass
class Notification:
    title: str = ""
    text: str = ""
    sub_text: str = ""
    ticker: str = ""
    small_icon: str = ""
    large_icon: str | None = None
    when_ms: int = 0
    auto_cancel: bool = False
    ongoing: bool = False
    defaults: int = 0
    vibrate: list[int] = field(default_factory=list)
    progress: tuple[int, int, bool] | None = None
    priority: str = "DEFAULT"
    channel_id: str | None = None
    content_intent: dict | None = None


class MockNotificationManager:
    def __init__(self, target_api: int):
        self.target_api = target_api
        self.channels: dict[str, str] = {}
        self.active: dict[int, Notification] = {}

    def create_channel(self, channel_id: str, importance: str) -> None:
        self.channels[channel_id] = importance

    def notify(self, nid: int, notification: Notification) -> dict:
        if not notification.small_icon:
            return {"posted": False, "reason": "missing_small_icon"}
        if self.target_api >= 26:
            if not notification.channel_id or notification.channel_id not in self.channels:
                return {"posted": False, "reason": "missing_notification_channel_api26"}
        self.active[nid] = notification
        return {"posted": True, "active_ids": sorted(self.active)}

    def click(self, nid: int) -> dict:
        n = self.active.get(nid)
        if not n:
            return {"clicked": False}
        if n.auto_cancel:
            del self.active[nid]
        return {"clicked": True, "still_active": nid in self.active, "target": n.content_intent}

    def cancel(self, nid: int) -> None:
        self.active.pop(nid, None)

    def cancel_all(self) -> None:
        self.active.clear()


def build_pending_intent(
    registry: dict[str, dict], key: str, extras: dict, flags: int, target_api: int
) -> dict | None:
    if target_api >= 31 and not (flags & FLAG_IMMUTABLE):
        raise ValueError("API 31+ requires FLAG_IMMUTABLE or FLAG_MUTABLE")
    exists = key in registry
    if flags & FLAG_NO_CREATE:
        return registry.get(key)
    if flags & FLAG_CANCEL_CURRENT and exists:
        del registry[key]
    if flags & FLAG_UPDATE_CURRENT and exists:
        registry[key]["extras"].update(extras)
        return registry[key]
    obj = {"key": key, "extras": dict(extras), "one_shot": bool(flags & FLAG_ONE_SHOT), "fired": False}
    registry[key] = obj
    return obj


def main() -> None:
    # Case 1: Notification.Builder flow, notify, autoCancel click & cancel
    nm23 = MockNotificationManager(target_api=23)
    n1 = Notification(
        title="系统提醒",
        text="您有一条新消息待查收",
        sub_text="即时通信",
        ticker="收到新消息",
        small_icon="mipmap/ic_small",
        large_icon="mipmap/ic_large",
        when_ms=1700000000000,
        auto_cancel=True,
        defaults=DEFAULT_LIGHTS | DEFAULT_VIBRATE,
        vibrate=[0, 300, 500, 700],
        content_intent={"activity": "OtherActivity"},
    )
    post_res = nm23.notify(1, n1)
    click_res = nm23.click(1)
    n2 = Notification(title="下载中", text="50%", small_icon="mipmap/ic_dl", ongoing=True, progress=(100, 50, False))
    nm23.notify(2, n2)
    nm23.cancel(2)
    act1 = {
        "posted": post_res["posted"],
        "defaults_mask": n1.defaults,
        "after_click_active": click_res["still_active"],
        "after_cancel_count": len(nm23.active),
        "progress_tuple": list(n2.progress),
    }
    exp1 = {
        "posted": True,
        "defaults_mask": 6,
        "after_click_active": False,
        "after_cancel_count": 0,
        "progress_tuple": [100, 50, False],
    }

    # Case 2: Android 8.0+ (API 26+) NotificationChannel enforcement & priority mapping
    nm33 = MockNotificationManager(target_api=33)
    no_ch = nm33.notify(1, Notification(title="未设渠道", small_icon="mipmap/ic_s"))
    nm33.create_channel("chat_high", PRIORITY_TO_IMPORTANCE["HIGH"][2])
    with_ch = nm33.notify(1, Notification(title="已设渠道", small_icon="mipmap/ic_s", channel_id="chat_high", priority="HIGH"))
    act2 = {
        "without_channel": no_ch,
        "with_channel": with_ch,
        "priority_table_keys": list(PRIORITY_TO_IMPORTANCE.keys()),
        "channel_importance": nm33.channels["chat_high"],
    }
    exp2 = {
        "without_channel": {"posted": False, "reason": "missing_notification_channel_api26"},
        "with_channel": {"posted": True, "active_ids": [1]},
        "priority_table_keys": ["MAX", "HIGH", "DEFAULT", "LOW", "MIN"],
        "channel_importance": "IMPORTANCE_HIGH",
    }

    # Case 3: PendingIntent flags & API 31+ mutability requirement
    reg: dict[str, dict] = {}
    missing_pi = build_pending_intent(reg, "act_other", {}, FLAG_NO_CREATE | FLAG_IMMUTABLE, target_api=33)
    created_pi = build_pending_intent(reg, "act_other", {"msg": "v1"}, FLAG_UPDATE_CURRENT | FLAG_IMMUTABLE, target_api=33)
    updated_pi = build_pending_intent(reg, "act_other", {"msg": "v2"}, FLAG_UPDATE_CURRENT | FLAG_IMMUTABLE, target_api=33)
    api31_error = False
    try:
        build_pending_intent(reg, "act_legacy", {}, 0, target_api=33)
    except ValueError:
        api31_error = True
    act3 = {
        "no_create_when_absent": missing_pi,
        "updated_msg": updated_pi["extras"]["msg"],
        "same_object_updated": created_pi is updated_pi,
        "api31_missing_mutability_rejected": api31_error,
    }
    exp3 = {
        "no_create_when_absent": None,
        "updated_msg": "v2",
        "same_object_updated": True,
        "api31_missing_mutability_rejected": True,
    }

    # Case 4: Progress notification lifecycle (indeterminate -> determinate -> finished)
    stages = [
        (0, 0, True),
        (100, 40, False),
        (100, 100, False),
        (0, 0, False),  # removes progress bar
    ]
    act4 = {"stage_count": len(stages), "indeterminate_start": stages[0][2], "removed_end": stages[-1] == (0, 0, False)}
    exp4 = {"stage_count": 4, "indeterminate_start": True, "removed_end": True}

    cases = [
        {
            "name": "notification_builder_and_lifecycle",
            "summary": "验证 Notification.Builder 构建、默认提示位掩码、autoCancel 点击消除与 cancel 移除",
            "expected": exp1,
            "actual": act1,
            "passed": act1 == exp1,
        },
        {
            "name": "notification_channel_and_priority_levels",
            "summary": "验证 Android 8.0+ NotificationChannel 强制校验及 MAX/HIGH/DEFAULT/LOW/MIN 优先级映射",
            "expected": exp2,
            "actual": act2,
            "passed": act2 == exp2,
        },
        {
            "name": "pending_intent_flags_and_api31_mutability",
            "summary": "验证 PendingIntent 的 FLAG_NO_CREATE/UPDATE_CURRENT 与 API 31+ FLAG_IMMUTABLE 要求",
            "expected": exp3,
            "actual": act3,
            "passed": act3 == exp3,
        },
        {
            "name": "progress_notification_state_transitions",
            "summary": "验证 setProgress 从不确定态到确定进度再调用 (0,0,false) 移除进度条的状态迁移",
            "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-notification-lab/explore-tutorial-notification.py

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

下载课程关联工程包:Android

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

下载课程关联工程包:Android

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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