2.5.8 Notification(状态栏通知)详解
系统梳理 Notification 的基础与扩展布局、NotificationManager 与 Notification.Builder 五步发送流程、PendingIntent 标志位、5 级优先级对照表,并补充 Android 8.0+ NotificationChannel 与 Android 13 权限演进。
学完这一章,你能够
- 系统梳理 Notification 的基础与扩展布局、NotificationManager 与 Notification.Builder 五步发送流程、PendingIntent 标志位、5 级优先级对照表,并补充 Android 8.0+ NotificationChannel 与 Android 13 权限演进。
通知布局演进与设计组成
`Notification` 用于在系统状态栏与通知抽屉中向用户传递异步消息。相较于早期 Android 2.x 直接拼接字段的做法,Android 4.x 起统一采用 `Notification.Builder`(及兼容库 `NotificationCompat.Builder`)构建结构化通知,并可参考官方通知设计与 API 文档了解各版本演进。
标准通知卡片由 6 个基本元素组成:左侧大图标(`Icon/Photo`)、通知标题(`Title/Name`)、正文信息(`Message`)、时间戳(`Timestamp`,默认为发出时间,可通过 `setWhen()` 覆盖)、小图标(`Secondary Icon`)以及位于小图标左侧的附加内容文字(`Content Info`/`SubText`)。
自 Android 4.1(Jelly Bean)起,通知支持双指缩放或下拉展开的扩展布局(Expanded Layout),系统提供大文本(BigText)与大图预览(BigPicture)等样式,使用户无需跳转应用即可浏览更多消息上下文。
Notification 使用五步流程与 Builder 核心方法
通知机制围绕 `Notification`(数据载体)与 `NotificationManager`(系统管理服务)展开,标准发送流程为五步:① 通过 `getSystemService(NOTIFICATION_SERVICE)` 获取 `NotificationManager`;② 创建 `Notification.Builder`(或 `NotificationCompat.Builder`);③ 链式配置标题、正文、图标与跳转意图;④ 调用 `build()` 生成 `Notification` 对象;⑤ 调用 `mNManager.notify(id, notification)` 发出通知,后续可按 ID 调用 `cancel(id)` 或 `cancelAll()` 清除。
`Notification.Builder` 提供丰富的定制方法:`setContentTitle()`、`setContentText()`、`setSubText()`、`setTicker()`、`setWhen()`、`setSmallIcon()`(必需)与 `setLargeIcon()` 控制展示内容;`setAutoCancel(true)` 让用户点击通知后自动移除;`setDefaults()` 可按位组合 `DEFAULT_VIBRATE`、`DEFAULT_SOUND`、`DEFAULT_LIGHTS` 或 `DEFAULT_ALL`;也可通过 `setVibrate(long[])`、`setLights(argb, onMs, offMs)`(需配合 `Notification.FLAG_SHOW_LIGHTS`)和 `setSound(Uri)` 精细控制提醒;`setOngoing(true)` 将通知标记为常驻进行中任务(如音乐播放、文件下载);`setProgress(max, progress, indeterminate)` 用于展示确定进度条(完成后调用 `setProgress(0, 0, false)` 移除)或不确定加载条(`indeterminate=true`)。
`setContentIntent(PendingIntent)` 定义点击通知后的延迟跳转动作。`PendingIntent` 可包装启动 Activity、Service 或 Broadcast 的意图,其第四个参数标志位包括 `FLAG_ONE_SHOT`(仅生效一次)、`FLAG_NO_CREATE`(不存在则返回 `null`)、`FLAG_CANCEL_CURRENT`(取消旧实例再重建)与 `FLAG_UPDATE_CURRENT`(保留实例并更新附加数据);在 Android 12(API 31+)中必须显式组合 `FLAG_IMMUTABLE` 或 `FLAG_MUTABLE`。此外,`setPriority(int)` 在 Android 7.1 及以下版本按 `MAX`、`HIGH`、`DEFAULT`、`LOW`、`MIN` 五档调节排序与打扰程度(详见下表);**现代版本关键变更**:Android 8.0(API 26+)强制要求先通过 `createNotificationChannel()` 注册 `NotificationChannel` 并在构造 `Builder` 时绑定渠道 ID,通道重要度(`IMPORTANCE_*`)取代了单条通知的 `setPriority()`;Android 13(API 33+)还需动态申请 `POST_NOTIFICATIONS` 运行时权限。
发送与取消通知示例及小结
示例 `MainActivity` 通过两个按钮演示完整生命周期:点击发送按钮时,先构造指向 `OtherActivity` 的 `PendingIntent`,使用 `Notification.Builder` 设置标题、正文、副标题、状态栏滚动提示、大小图标、默认灯光与振动、自定义 `raw` 提示音以及 `setAutoCancel(true)`,经 `build()` 后调用 `notify(NOTIFYID_1, notify1)`;点击关闭按钮时则调用 `mNManager.cancel(NOTIFYID_1)` 移除通知。本站离线 Python 验证器实测了通知构建/自动消除、API 26+ 缺渠道拦截、五级优先级映射及 API 31+ `PendingIntent` 不可变标志校验。
原教程提供 `NotificationDemo.zip` 供下载(因继承停采策略未联网抓取,已登记至 `reviewed_source_attachments`)。在生产项目中建议统一使用 `NotificationCompat.Builder` 配合 `NotificationChannel`,以平滑兼容 Android 4.x 至 Android 14+ 全版本。
Notification 优先级(Priority)档位与用途说明
| 优先级 | 适用场景与系统表现 |
| MAX(Notification.PRIORITY_MAX) | 重要而紧急、时效性强且需要用户立即处理的通知(Android 8.0+ 对应高重要度渠道 IMPORTANCE_HIGH)。 |
| HIGH(Notification.PRIORITY_HIGH) | 用于即时通信、短消息或聊天等用户高度关注的提醒内容(Android 8.0+ 对应 IMPORTANCE_HIGH)。 |
| DEFAULT(Notification.PRIORITY_DEFAULT) | 常规默认优先级,用于无特殊紧急度要求的普通通知(Android 8.0+ 对应 IMPORTANCE_DEFAULT)。 |
| LOW(Notification.PRIORITY_LOW) | 低优先级事件提醒,可告知用户但无需强打扰(Android 8.0+ 对应 IMPORTANCE_LOW,无提示音)。 |
| MIN(Notification.PRIORITY_MIN) | 后台静默信息(如天气或位置更新),不在状态栏主动弹出提醒,仅在下拉通知抽屉后可见(Android 8.0+ 对应 IMPORTANCE_MIN)。 |
运行 Notification.Builder 生命周期、Android 8+ NotificationChannel 与 PendingIntent 标志离线验证
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
缺少 NotificationChannel:Android 8.0+ 必须先向 NotificationManager 注册通知渠道,并在 Notification.Builder(context, channelId) 中绑定已注册的 channelId,否则系统会直接丢弃通知。