Android 大通知(Expanded Notification)实战:解读 cw-omnibus 的 BigNotify 示例与 InboxStyle 展开视图
Android 大通知(Expanded Notification)实战:解读 cw-omnibus 的 BigNotify 示例与 InboxStyle 展开视图
cw-omnibus 是《The Busy Coder's Guide to Android Development》一书配套的示例源码仓库,其中 Notifications/BigNotify 演示的是最典型的大通知(Big Notification / Expanded Notification)场景:应用启动后立即向系统通知栏发布一条**带展开视图(expanded view)**的通知,然后立刻退出。本文将以该示例的 README 声明为主线,结合 MainActivity.java 的完整源码、资源文件与构建配置,讲解如何用 NotificationCompat.InboxStyle 构建可展开的多行通知,并覆盖通知渠道、通知优先级、操作按钮与 PendingIntent 等配套知识点。读完本文,你将掌握一套可直接复制的"发完即走"大通知实现方案。
示例定位:一个"即发即走"的大通知演示
Notifications/BigNotify/README.markdown 对示例的定位描述非常简洁:
This sample Android app demonstrates a
Notificationwith an expanded view.
也就是说,这个示例的全部目的就是演示"一条带展开视图的 Notification"。它与 Notifications/ 目录下的其他示例(如 BigLocal、Stacked、Pages、CustomView)同属通知主题,但聚焦点不同:BigNotify 只关心用标准扩展样式把普通通知升级为可展开的大通知。
从项目结构看,这是一个极简的独立工程:
Notifications/BigNotify/
├── app/
│ ├── build.gradle # 应用模块构建配置
│ └── src/main/
│ ├── AndroidManifest.xml # 仅一个 Activity,透明无标题栏主题
│ ├── java/com/commonsware/android/bignotify/
│ │ └── MainActivity.java # 唯一源码:发布大通知
│ └── res/
│ ├── values/strings.xml # 通知文案
│ └── drawable-*/ic_launcher.png
├── build.gradle # 顶层构建配置
├── settings.gradle # include ':app'
├── gradle/wrapper/gradle-wrapper.properties
├── project.properties # 遗留 Ant 构建目标文件
└── proguard-project.txt # ProGuard 规则占位
整个应用的行为可以用一句话概括:用户点击桌面图标 → MainActivity 在 onCreate() 中构建并发布一条 Inbox 风格的大通知 → 立即调用 finish() 结束 Activity,留给用户的就是通知栏里那条可展开的通知。这正是 AndroidManifest.xml 中为 Activity 声明 @android:style/Theme.Translucent.NoTitleBar 透明主题的原因——Activity 本身不需要任何界面,它只是一次性的"通知发射器"。
什么是"展开视图":从普通通知到大通知
Android 的通知在收起状态下只能展示一行摘要信息(标题 + 单行正文 + 小图标)。**展开视图(expanded view)**则是用户主动展开通知(如双指下拉,或在新版本系统中长按/下拉通知)后看到的大尺寸内容区。要提供展开视图,最标准的做法是给通知设置一个"大样式"(big style)。Android 框架与 Support Library 提供了三种经典的大样式:
- BigTextStyle:适合长文本,展开后显示大段文字;
- BigPictureStyle:适合图片,展开后展示一张大图;
- InboxStyle:适合多条短信息,展开后以"行"为单位罗列若干条目,并配一个摘要文本——
BigNotify采用的正是这种样式。
从源码可以确认,示例通过 NotificationCompat.InboxStyle(Support Library 版本)把普通 Builder 包装成可展开的通知。它的典型适用场景包括邮件收件箱、聊天消息列表、"下载完成"等需要一次性展示多条信息的通知。
核心源码逐段解析
BigNotify 的全部逻辑都集中在 MainActivity.java 中,下面按执行顺序拆解。
第一步:获取 NotificationManager 并准备通知渠道
NotificationManager mgr=
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O &&
mgr.getNotificationChannel(CHANNEL_WHATEVER)==null) {
mgr.createNotificationChannel(new NotificationChannel(CHANNEL_WHATEVER,
"Whatever", NotificationManager.IMPORTANCE_DEFAULT));
}
- 常量
CHANNEL_WHATEVER="channel_whatever"是通知渠道 ID,NOTIFY_ID=1337是通知 ID。 - Android 8.0(API 26)起,所有通知都必须挂在某个通知渠道(NotificationChannel)上。源码用
Build.VERSION.SDK_INT >= Build.VERSION_CODES.O做版本判断,并在渠道不存在时才创建,渠道名"Whatever"、重要级别IMPORTANCE_DEFAULT。这样既保证了 O 及以上系统的合法性,又不影响旧版本运行。 - 渠道重要级别直接影响通知的打扰行为(声音/震动/横幅),
IMPORTANCE_DEFAULT表示默认重要级别。
第二步:buildNormal()——构建普通通知主体
private NotificationCompat.Builder buildNormal() {
NotificationCompat.Builder b=
new NotificationCompat.Builder(this, CHANNEL_WHATEVER);
b.setAutoCancel(true)
.setContentTitle(getString(R.string.download_complete))
.setContentText(getString(R.string.fun))
.setContentIntent(buildPendingIntent(Settings.ACTION_SECURITY_SETTINGS))
.setSmallIcon(android.R.drawable.stat_sys_download_done)
.setPriority(Notification.PRIORITY_HIGH)
.addAction(android.R.drawable.ic_media_play,
getString(R.string.play),
buildPendingIntent(Settings.ACTION_SETTINGS));
return(b);
}
关键点逐项说明:
| 方法 | 参数/取值 | 作用 |
|---|---|---|
setAutoCancel(true) |
布尔值 | 用户点击通知后自动从通知栏移除 |
setContentTitle |
download_complete("Download complete!") |
收起状态下的标题 |
setContentText |
fun("Tap me to view the file") |
收起状态下的单行正文 |
setContentIntent |
PendingIntent,动作 Settings.ACTION_SECURITY_SETTINGS |
点击通知跳转到系统安全设置 |
setSmallIcon |
android.R.drawable.stat_sys_download_done |
使用系统内置的"下载完成"小图标 |
setPriority |
Notification.PRIORITY_HIGH |
高优先级,更容易打扰用户、显示在更靠前位置 |
addAction |
系统图标 ic_media_play + "Play" + 跳转系统设置 |
在通知上附加一个操作按钮 |
注意 setPriority 这里使用的是框架常量 Notification.PRIORITY_HIGH(而非 NotificationCompat 版本),这是 BigNotify 与同目录下 BigLocal 的一个细微差异——后者使用的是 NotificationCompat.PRIORITY_DEFAULT,并额外调用了 setDefaults(Notification.DEFAULT_ALL)、setTicker(...) 和 setLocalOnly(true)。
PendingIntent 的构建方式也很直接:
private PendingIntent buildPendingIntent(String action) {
Intent i=new Intent(action);
return(PendingIntent.getActivity(this, 0, i, 0));
}
这里没有显式指定 Intent 的 setPackage,因此点击通知/按钮时由系统解析对应的隐式动作(Settings.ACTION_SECURITY_SETTINGS、Settings.ACTION_SETTINGS)。
第三步:用 InboxStyle 把普通通知升级为展开视图
这是整个示例的核心所在:
NotificationCompat.Builder normal=buildNormal();
NotificationCompat.InboxStyle big=
new NotificationCompat.InboxStyle(normal);
mgr.notify(NOTIFY_ID,
big.setSummaryText(getString(R.string.summary))
.addLine(getString(R.string.entry))
.addLine(getString(R.string.another_entry))
.addLine(getString(R.string.third_entry))
.addLine(getString(R.string.yet_another_entry))
.addLine(getString(R.string.low)).build());
- 把已经构建好的
NotificationCompat.Builder normal直接传入NotificationCompat.InboxStyle构造函数,InboxStyle 会继承该 Builder 上的全部设置(标题、图标、优先级、操作按钮等)。 setSummaryText("Summary Goes Here")设置展开区域的摘要行;- 连续 5 次
addLine(...)加入 5 行条目,文案依次来自 strings.xml:entry("An Entry")、another_entry("Another Entry")、third_entry("A Third Entry")、yet_another_entry("Yet Another Entry")、low("How Low Can We Go?")。
最终效果是:通知收起时显示 download_complete 标题与单行正文;用户展开后看到"Summary Goes Here"摘要加上 5 行条目——一条标准的"收件箱"式大通知。addLine() 理论上可以调用多次,行的数量由你按需添加,这正是 InboxStyle 与单一 setContentText 的本质区别。
第四步:发布通知并立即退出
mgr.notify(NOTIFY_ID, ... .build());
finish();
mgr.notify(NOTIFY_ID, notification)以1337为通知 ID 发布通知;相同 ID 再次发布会更新该通知,如需区分多条通知应使用不同 ID。- 发布成功后立刻
finish()关闭 Activity。配合透明无标题栏主题,用户几乎感知不到应用界面的存在——这是一个干净利落的"后台式"通知发布模式,常用于"下载完成提醒"这类一次性通知场景。
资源与构建配置解读
文案资源
strings.xml 集中定义了通知的全部文案:
<string name="app_name">BigNotificationSample</string>
<string name="sample">Sample Inbox Notification</string>
<string name="download_complete">Download complete!</string>
<string name="fun">Tap me to view the file</string>
<string name="exception">EXCEPTION!</string>
<string name="play">Play</string>
<string name="summary">Summary Goes Here</string>
<string name="entry">An Entry</string>
<string name="another_entry">Another Entry</string>
<string name="third_entry">A Third Entry</string>
<string name="yet_another_entry">Yet Another Entry</string>
<string name="low">How Low Can We Go?</string>
代码中所有文案都通过 getString(R.string.xxx) 引用,而不是硬编码字符串——这是可本地化(localization)的基本要求。
清单文件
AndroidManifest.xml 声明了唯一入口:
<activity
android:name=".MainActivity"
android:theme="@android:style/Theme.Translucent.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
注意:示例是老式写法,使用 <activity> 直接作为应用入口(未使用 androidx/appcompat),并通过 Theme.Translucent.NoTitleBar 实现"无界面的透明启动"。示例没有申请任何权限,因为发布普通通知不需要额外权限(Android 13+ 的通知运行时权限不在该示例的覆盖范围内,示例 targetSdkVersion 为 26)。
构建配置
app/build.gradle 明确了编译环境:
apply plugin: 'com.android.application'
dependencies {
implementation 'com.android.support:support-compat:26.1.0'
}
android {
compileSdkVersion 26
buildToolsVersion '27.0.3'
defaultConfig {
minSdkVersion 16
targetSdkVersion 26
versionCode 1
versionName "1.0"
}
}
minSdkVersion 16:支持 Android 4.1 及以上;compileSdkVersion 26/targetSdkVersion 26:面向 Android 8.0;- 仅依赖
com.android.support:support-compat:26.1.0,NotificationCompat、NotificationManagerCompat都来自这个依赖,这也是示例能在 API 16~25 上兼容工作的原因。
顶层 build.gradle 使用 Android Gradle 插件 3.1.4,gradle-wrapper.properties 指向 gradle-4.4-all 发行版。另外,project.properties 中的 target=android-19 是早期 Ant 构建体系遗留的产物,Gradle 构建可以忽略它。
如何导入与运行
- Android Studio 导入:直接用 Android Studio 打开
Notifications/BigNotify目录(settings.gradle已声明include ':app'),等待 Gradle Sync 即可。若本机未安装compileSdkVersion 26对应 SDK,可按仓库根 README.markdown 的建议调整compileSdkVersion与buildToolsVersion。 - 命令行 Gradle:仓库出于安全考虑没有提交
gradlew脚本及其 JAR,只保留了 wrapper 属性文件。因此命令行构建需要本机安装与 wrapper 版本匹配的 Gradle(wrapper 指向 4.4;仓库根 README 提到其自身测试环境使用 Gradle 3.3),再在目录下执行gradle assembleDebug或gradle installDebug等任务。 - 安全提醒:根 README 特别强调,导入前务必检查
gradle-wrapper.properties,防止被恶意替换为指向被篡改 Gradle 安装包的下载地址。
运行后:点击应用图标 → 屏幕一闪而过 → 通知栏出现"Download complete!"通知;展开它即可看到 InboxStyle 的摘要与 5 行条目,通知上还有一个"Play"操作按钮。
同主题示例横向参考
Notifications/ 目录下还有几个与"展开/大通知"直接相关的姊妹示例,适合对照阅读:
| 示例 | README 定位 | 与 BigNotify 的差异(依据源码) |
|---|---|---|
| BigLocal | 仅本机显示、不下发到 Wear 的通知 | 与 BigNotify 几乎同构,额外使用 setLocalOnly(true)、setTicker(...)、setDefaults(Notification.DEFAULT_ALL) 与 NotificationCompat.PRIORITY_DEFAULT |
| Stacked | 堆叠通知(尤其针对 Wear) | 用 setGroup(...) / setGroupSummary(true) 把多条通知聚合为一个组,并用 InboxStyle 生成摘要通知 |
| Pages | Wear 设备上的多页通知 | 用 NotificationCompat.WearableExtender().addPage(...) 为同一通知添加附加页面 |
| CustomView | 用自定义视图替代标准通知样式 | 不使用标准大样式,改为自定义 RemoteViews |
其中 Stacked 与 Pages 的源码均位于各自的 app/src/main/java/com/commonsware/android/ 目录下,同样采用 NotificationCompat.InboxStyle 作为展开样式的基础,并都用 NotificationManagerCompat.from(this) 发布通知——这提供了另一种发布途径(NotificationManagerCompat 内部自动处理权限与兼容性问题)。
实践要点小结
- 大通知三件套:
BigTextStyle管长文、BigPictureStyle管大图、InboxStyle管多条目。BigNotify选用了 InboxStyle,最适合"下载完成 + 若干条目"式通知。 - InboxStyle 的构造方式:可直接把已配置好的
NotificationCompat.Builder传入new NotificationCompat.InboxStyle(builder),展开样式会继承 Builder 上的全部属性,随后用setSummaryText()与addLine()填充内容。 - 渠道优先:API 26+ 必须先创建
NotificationChannel,BigNotify用Build.VERSION.SDK_INT判断并惰性创建,这一写法可直接复用于任何项目。 - 即发即走:透明主题 Activity +
finish()是"一次性通知发射器"的经典模式,适合无需界面的后台提醒。 - 文案与图标:所有文案收拢到
strings.xml,小图标使用系统内置android.R.drawable.stat_sys_download_done,避免引入额外资源。 - 配套参考:需要本机专用、分组堆叠或 Wear 多页能力时,分别参考
BigLocal、Stacked、Pages三个姊妹示例的实现。