Thunderbird for Android 通知系统完整指南:从命令模式架构到 System/In-App 双通道通知实战

原创2026-09-22 11:55:111,739 阅读
文章标签:移动开发原生移动

Thunderbird for Android 通知系统完整指南:从命令模式架构到 System/In-App 双通道通知实战

Thunderbird for Android(前身 K-9 Mail)在 feature/notification 模块中构建了一套灵活、可扩展的通知系统:同一份通知数据模型可以同时投递到系统通知栏(System Notification)和应用内 UI(In-App Notification),对外暴露统一 API,内部通过**命令模式(Command Pattern)**实现请求与平台渲染的彻底解耦。本指南以该模块的 README、架构文档 与 样式文档 为核心,结合源码与测试,带你完成从"注入 NotificationSender 发出第一条通知"到"设计正确的通知类型/严重级别/样式"的完整闭环,并深入底层理解其实现原理。

模块组织:通知系统代码分布在 feature/notification/api(核心接口与类)、feature/notification/impl(实现)、feature/notification/testing(测试替身)三个模块中,API 模块同时面向 KMP(Kotlin Multiplatform)与 Android 使用。

快速开始:创建并发送一条通知

从零到一条已投递的通知只需三步。

第 1 步:注入 NotificationSender

NotificationSender 是一个函数式接口(fun interface),在 NotificationSender.kt 中定义:它接收一个 Notification,返回一个发射每个已执行命令结果的 Flow<NotificationCommandOutcome<Notification>>。

// MyViewModel.kt
class MyViewModel(
    private val notificationSender: NotificationSender,
) : ViewModel() {
    // ...
}

// KoinModule.kt
val myFeatureModule = module {
    // ...
    viewModel {
        MyViewModel(
            notificationSender = get(),
        )
    }
}

第 2 步:创建 Notification 实例

创建一个同时实现了 SystemNotification、InAppNotification(或二者之一)的具体类型。可以直构造,也可以通过工厂构造(推荐用于本地化文本,见下文"本地化与字符串处理")。

// Example: Authentication error shown as both system and in‑app
val notification = AuthenticationErrorNotification(
    accountNumber = accountNumber,
    accountUuid = accountUuid,
    accountDisplayName = accountDisplayName,
)

第 3 步:发送并处理结果

viewModelScope.launch {
    notificationSender
        .send(notification)
        .collect { outcome ->
            outcome.handle(
                onSuccess = { commandOutcome ->
                    // Optional: update UI/log
                },
                onFailure = { error ->
                    // Optional: show an error message/log
                },
            )
        }
}

发送返回的是一个冷 Flow,逐个发射每条命令的执行结果(Outcome 包装,成功为 CommandOutcomeSuccess,失败为 CommandOutcomeFailure(throwable))。这意味着你可以精确感知每条命令是否真正执行成功,从而做 UI/日志联动。

通知类型与选型

Thunderbird 使用统一的 Notification 模型,派生出两种专用类型:

  • SystemNotification — 标准 Android 系统通知(需要运行时权限;UI 由操作系统决定)。
  • InAppNotification — 仅在应用 UI 内显示的消息(无需权限;完全由应用控制)。

如何选择正确的类型

回答一个关键问题——通知何时必须触发:

  1. 后台? 使用 SystemNotification。
  2. 前台? 使用 InAppNotification。
  3. 两者都要? 在你的类型上同时实现两个接口(单一数据负载、两个渲染目标)。

类型对比矩阵

能力 SystemNotification InAppNotification
应用在后台时出现 ✅ ❌
应用在前台时出现 ✅ ✅
需要运行时权限 ✅(POST_NOTIFICATIONS) ❌
UI 控制权在 Android 操作系统 应用(Compose)
典型用途 新邮件、后台错误 引导、内联错误、瞬时反馈

[!TIP] 对于关键问题,如果需要在应用打开时仍保持持久、全局可见性,请同时实现两者,并选择下方合适的 in-app 样式。

两种类型的详细数据模型差异见 Notification 数据模型。

严重级别(Severity)与行为差异

每条通知必须定义一个 NotificationSeverity,用于驱动用户打扰程度与视觉样式。该枚举定义在 NotificationSeverity.kt,每个枚举值都带有一个 dismissable: Boolean 标志——这直接决定了系统通知能否被用户划掉。

严重级别 何时使用 期望用户动作 SystemNotification 行为 InApp(BannerGlobal)颜色提示
Fatal 阻塞关键任务 立即解决 不可划除 Error 色
Critical 中断核心流程 通常需要处理 不可划除 Error 色
Warning 潜在问题/限制 通常建议处理 可划除 Warning 色
Temporary 暂时中断/延迟 可能自愈;需告知 可划除 Information 色
Information 仅状态/上下文 无需动作 可划除 Information 色

示例:

  • Fatal — 认证错误;动作:重试、提供其他凭据。
  • Critical — "发送消息失败";动作:重试。
  • Warning — "邮箱已使用 90%";动作:管理存储空间。
  • Temporary — "当前离线;消息稍后发送"。
  • Information — "上次同步成功"。

注意:当前 NotificationSeverity 只影响 in-app 通知的样式(详见 样式文档的 Severity 章节),系统通知的外观由 Android 系统按渠道重要性(Channel Importance)决定。

样式选项

1. 系统通知样式(System Notification Styles)

默认情况下,系统通知显示 图标 + 标题 + 内容文本(样式为 Undefined)。支持样式:

  • Undefined(基础)
  • BigTextStyle — 展开后的大文本块
  • InboxStyle — 多行短文本(如邮件预览摘要)

这些样式在源码中定义为 sealed interface SystemNotificationStyle.kt,并提供 systemNotificationStyle { ... } DSL 构建函数。其中 InboxStyle.lines 最多支持 5 行字符串。

BigTextStyle 示例

data class NewMailSingleMail(
    override val accountUuid: String,
    val accountName: String,
    val summary: String,
    val sender: String,
    val subject: String,
    val preview: String,
    override val icon: NotificationIcon = NotificationIcons.NewMailSingleMail,
) : MailNotification() {
    override val title: String = sender
    override val contentText: String = subject
    override val systemNotificationStyle: SystemNotificationStyle = systemNotificationStyle {
        bigText(preview)
    }
}

各属性职责:title 显示通知第一行文本(这里取发件人);contentText 在折叠态显示正文;bigText(preview) 传入的字符串在展开态作为正文显示。

BigText 系统通知折叠状态

BigText 系统通知展开状态

InboxStyle 示例(多条消息摘要)

@ConsistentCopyVisibility
data class NewMailSummaries private constructor(
    override val accountUuid: String,
    override val title: String,           // collapsed title
    override val contentText: String,     // collapsed content
    val expandedTitle: String,
    val summary: String,
    val lines: List<CharSequence>,
    override val icon: NotificationIcon = NotificationIcons.NewMailSummaries,
) : MailNotification() {
    override val systemNotificationStyle: SystemNotificationStyle = systemNotificationStyle {
        inbox {
            title(expandedTitle)
            summary(summary)
            lines(lines = lines.toTypedArray())
        }
    }

    companion object {
        suspend operator fun invoke(
            accountUuid: String,
            accountDisplayName: String,
            previews: List<CharSequence>,
        ): NewMailSummaries = NewMailSummaries(
            accountUuid = accountUuid,
            title = getPluralString(
                resource = Res.strings.new_mail_summaries_collapsed_title,
                quantity = previews.size,
                previews.size,
                accountDisplayName,
            ),
            contentText = getString(Res.strings.new_mail_summaries_content_text),
            expandedTitle = getPluralString(
                resource = Res.strings.new_mail_summaries_expanded_title,
                quantity = previews.size,
                previews.size,
            ),
            summary = getString(
                resource = Res.strings.new_mail_summaries_additional_messages,
                previews.size,
                accountDisplayName,
            ),
            lines = previews,
        )
    }
}

配合的复数/字符串资源(位于 feature/notification/api 的 Compose Resources 中):

<resources>
    <plurals name="new_mail_summaries_collapsed_title">
        <item quantity="one">You've received %1$d new message on %2$s</item>
        <item quantity="other">You've received %1$d new messages on %2$s</item>
    </plurals>
    <string name="new_mail_summaries_content_text">Expand to preview</string>
    <plurals name="new_mail_summaries_expanded_title">
        <item quantity="one">%1$d new message</item>
        <item quantity="other">%1$d new messages</item>
    </plurals>
    <string name="new_mail_summaries_additional_messages">+ %1$d more on %2$s</string>
</resources>

各字段说明:title 在折叠态显示第一行;contentText 在折叠态显示正文;expandedTitle 在展开态显示第一行;summary 显示在 Inbox 大模板详情区之后的第一行;lines 显示摘要区中的各条预览。

[!IMPORTANT] 系统通知 UI 在不同 Android 版本与 OEM 之间可能存在差异,但总体观感一致。上述截图基于 Android 16 + Pixel 7 Pro 拍摄。

另请注意:InboxStyle 的 lines 参数在 SystemNotificationStyle.kt 中被约束为最多 5 行,超出部分由系统截断处理。

2. 应用内通知样式(In-App Notification Styles)

根据 UX 意图选择一种,未来可能增加更多样式。完整对比与截图见 notification-styles.md。

Banner Global

持久、非阻塞的全局状态提示。

用于:

  • 全局警告(如离线、加密密钥不可用)
  • 账户配置流程:需要持续指示的错误/成功/信息

不要用于:

  • 非配置类消息(优先用 Banner Inline 或 Snackbar)
  • 流程阻塞场景(优先用 Dialog)

严重级别驱动的 Banner Global 颜色变化:Error/Warning/Information 色系分别对应 Fatal&Critical / Warning / Temporary&Information。

Banner Inline

局限于当前屏幕的内联阻塞/近阻塞反馈。

用于:

  • 影响屏幕主要功能的关键问题
  • 用户在有效继续前必须先处理的错误

不要用于:

  • 真正的阻塞流程(用 Dialog)
  • 全局状态(用 Banner Global)
  • 存在更深根因时的次级/症状消息

Snackbar

瞬态、非中断的反馈;可附带一个动作。

用于:

  • 动作反馈与快速纠正选项

不要用于:

  • 必须中断或阻塞的错误(用 Dialog)
  • 统一收件箱同步错误(优先用 Banner 类型)

Dialog

用于权限或必须操作项的短促、中断式提示。

用于:

  • 请求通知权限并提供清晰理由

不要用于:

  • 一般错误或非关键权限(如通讯录)
  • 与省电模式绑定的后台活动权限

应用内 Snackbar 示例

应用内 Dialog(通知权限)示例

本地化与字符串处理

由于 :feature:notification:api 是 KMP 模块,构建文本时应优先在 suspend 工厂函数中使用 Compose Resources。

KMP 友好(suspend 工厂)— 推荐

可以用 companion object + suspend operator fun invoke() 创建挂起工厂:

@ConsistentCopyVisibility
data class AuthenticationErrorNotification private constructor(
    override val title: String,
    override val contentText: String,
    override val channel: NotificationChannel,
    override val icon: NotificationIcon = NotificationIcons.AuthenticationError,
) : AppNotification(), SystemNotification, InAppNotification {

    companion object {
        suspend operator fun invoke(
            accountUuid: String,
            accountDisplayName: String,
        ): AuthenticationErrorNotification = AuthenticationErrorNotification(
            title = getString(
                resource = Res.string.notification_authentication_error_title,
                accountDisplayName,
            ),
            contentText = getString(resource = Res.string.notification_authentication_error_text),
            channel = NotificationChannel.Miscellaneous(accountUuid = accountUuid),
        )
    }
}

或者使用与类型同名的挂起工厂函数:

@ConsistentCopyVisibility
data class AuthenticationErrorNotification internal constructor(
    override val title: String,
    override val contentText: String,
    override val channel: NotificationChannel,
    override val icon: NotificationIcon = NotificationIcons.AuthenticationError,
) : AppNotification(), SystemNotification, InAppNotification

suspend fun AuthenticationErrorNotification(): AuthenticationErrorNotification = AuthenticationErrorNotification(
    title = getString(
        resource = Res.string.notification_authentication_error_title,
        accountDisplayName,
    ),
    contentText = getString(resource = Res.string.notification_authentication_error_text),
    channel = NotificationChannel.Miscellaneous(accountUuid = accountUuid),
)

注意:AppNotification 是抽象类,也是官方文档与源码 AppNotification.kt 中指定的创建新通知类型时应继承的基类——它默认实现 accessibilityText = title、createdAt = 当前 UTC 时间、actions = emptySet(),极大简化了新类型的创建。

Android-only 模块 — 使用带 Android Resources 的工厂类

Android 模块需要 Context,因此需在工厂类中获取资源。把需要的 *ResourceManager 注入构造函数:

class AuthenticationErrorNotificationFactory(
    private val strings: StringsResourceManager,
) {
    fun create(
        accountUuid: String,
        accountDisplayName: String,
    ): AuthenticationErrorNotification = AuthenticationErrorNotification(
        title = strings.stringResource(
            resourceId = R.string.notification_authentication_error_title,
            accountDisplayName,
        ),
        contentText = strings.stringResource(
            resourceId = R.string.notification_authentication_error_text
        ),
        channel = NotificationChannel.Miscellaneous(accountUuid = accountUuid),
    )
}

通知渠道(NotificationChannel)

SystemNotification 必须指定一个 channel。渠道在 NotificationChannel.kt 中定义为 sealed class,内置三种常用渠道,其 importance 直接映射 Android 渠道重要性:

  • Messages(accountUuid, suffix) — 新消息渠道,id 形如 messages_channel_$accountUuid$suffix,重要性 Default。
  • Miscellaneous(accountUuid?) — 杂项渠道,无账户时 id 为 misc,有账户时为 miscellaneous_channel_$accountUuid,重要性 Low。
  • PushService — 推送服务渠道(连接状态/错误),id 为 push,重要性 Low。

重要性枚举 NotificationChannelImportance 与 Android 常量一一对应:None(不显示)、Min(仅面板内折叠显示)、Low(通知栏可显示但不发声打扰)、Default(随处显示、发声、不视觉侵入)、High(随处显示、发声并弹窗,可能使用全屏 Intent)。

向用户展示通知

系统通知 — 权限处理

系统通知需要 android.permission.POST_NOTIFICATIONS。模块不会自动检查;请先调用 PermissionChecker 再相应处理。

class CheckPermission(
    private val permissionChecker: PermissionChecker,
) : UseCase.CheckPermission {
    override fun invoke(permission: Permission): PermissionState {
        return permissionChecker.checkPermission(permission)
    }
}

class ViewModel(checkPermission: UseCase.CheckPermission) : BaseViewModel(initialState = State()) {
    init {
        updateState {
            it.copy(
                permissionState = when (checkPermission(Permission.Notifications)) {
                    PermissionState.GrantedImplicitly -> UiPermissionState.Unknown
                    PermissionState.Granted -> UiPermissionState.Granted
                    PermissionState.Denied -> UiPermissionState.Unknown
                },
            )
        }
    }
}

一旦授权,操作系统将按你定义的样式渲染通知。权限请求的交互界面在实现侧由 ErrorNotificationsDialogFragment(impl 的 androidMain)承载。

应用内通知 — InAppNotificationScaffold

将需要应用内通知的屏幕包裹在 InAppNotificationScaffold 中——它是 Scaffold 的超集,具有通知感知布局。源码位于 InAppNotificationScaffold.kt。

@Composable
fun InAppNotificationScaffold(
    modifier: Modifier = Modifier,
    // 1.
    enabled: ImmutableSet<DisplayInAppNotificationFlag> = DisplayInAppNotificationFlag.AllNotifications,
    // 2
    topBar: @Composable () -> Unit = {},
    bottomBar: @Composable () -> Unit = {},
    // 3
    snackbarHostState: SnackbarHostState = rememberSnackbarHostState(),
    // 4
    floatingActionButton: @Composable () -> Unit = {},
    floatingActionButtonPosition: ScaffoldFabPosition = ScaffoldFabPosition.End,
    // 5
    onNotificationActionClick: (NotificationAction) -> Unit = {},
    // 6
    content: @Composable (PaddingValues) -> Unit,
) { /* ... */ }

参数说明

  1. 通过 enabled 标志限制本屏幕要显示哪些样式(如仅 Snackbar、仅 Banner 等)。
  2. topBar/bottomBar 槽位参数与 Scaffold 用法一致。
  3. 提供 SnackbarHostState;它用于 SnackbarNotification 样式以及你自定义的 snackbar。
  4. FAB 参数与 Scaffold 一致。
  5. 用户点击 in-app 通知动作时回调 onNotificationActionClick。
  6. 必须在 content 中消费 PaddingValues;否则通知显示时布局无法正确适配。

在实现上,该组件内部通过 InAppNotificationHost(InAppNotificationHost.kt)监听事件流并渲染通知;BannerGlobalNotificationHost 与 BannerInlineNotificationListHost 分别承载全局横幅与内联横幅列表。宿主测试(BannerGlobalNotificationHostTest.kt 等)验证了这些布局在宿主环境下的正确行为。

架构:命令模式实现原理

完整架构深入分析见 通知架构文档。以下为核心摘要。

架构摘要

系统分为四个逻辑组:

  • Client(客户端) — 构建 Notification 负载并调用 Invoker,通常是 ViewModel。
  • Invoker(调用者) — NotificationSender / DefaultNotificationSender;使用工厂创建命令并执行它们。
  • Command(命令) — 封装一个 Notification + NotificationNotifier,暴露 execute()。
  • Receiver(接收者) — 展示通知的平台代码(SystemNotificationNotifier 使用 NotificationManager;InAppNotificationNotifier 使用事件总线)。
---
config:
  look: neo
  layout: elk
---
classDiagram
    class Notification
    namespace Client {
        class SomeAppViewModel {
            - sender: NotificationSender
            + onSendNotificationClicked()
        }
    }
    namespace Invoker {
        class NotificationSender {
            <<interface>>
            + send(notification: Notification) Flow~Outcome~
        }
        class DefaultNotificationSender {
            - commandFactory: NotificationCommandFactory
        }
        class NotificationCommandFactory {
            + create(notification: Notification) List~NotificationCommand~
        }
    }
    namespace Command {
        class NotificationCommand~Notification~ {
            <<abstract>>
            # notification: Notification
            # notifier: NotificationNotifier~Notification~
            + execute() Outcome
        }
        class SystemNotificationCommand
        class InAppNotificationCommand
        class Outcome
        class CommandOutcome {
            <<interface>>
        }
        class CommandOutcomeSuccess {
            <<data>>
        }
        class CommandOutcomeFailure {
            <<data>>
            + throwable: Throwable
        }
    }
    namespace Receiver {
        class NotificationNotifier~Notification~ {
            <<interface>>
            + show(id: NotificationId)
            + dispose()
        }
        class SystemNotificationNotifier
        class InAppNotificationNotifier
    }
    namespace Platform Dependencies {
        class NotificationManager
    }
    class InAppNotificationEventBus
    class NotificationRegistry
    DefaultNotificationSender --|> NotificationSender
    SystemNotificationCommand --|> NotificationCommand
    InAppNotificationCommand --|> NotificationCommand
    SystemNotificationNotifier --|> NotificationNotifier
    InAppNotificationNotifier --|> NotificationNotifier
    CommandOutcomeSuccess --|> CommandOutcome
    CommandOutcomeFailure --|> CommandOutcome
    SomeAppViewModel "1" --* "1" NotificationSender: uses
    SomeAppViewModel ..> Notification: creates
    DefaultNotificationSender --> NotificationCommandFactory: uses
    NotificationCommandFactory ..> SystemNotificationCommand: creates
    NotificationCommandFactory ..> InAppNotificationCommand: creates
    NotificationCommand "1" --* "1" NotificationNotifier: has-a
    NotificationCommand ..> Outcome: returns
    SystemNotificationNotifier ..> NotificationManager: uses
    InAppNotificationNotifier ..> InAppNotificationEventBus: uses
    InAppNotificationNotifier ..> NotificationRegistry: uses
    Outcome --* "1" CommandOutcome

Client(客户端)

在经典命令模式中,Client 常负责创建命令并设置接收者,但本实现简化了 Client 的角色。

  • 实现: 任意 ViewModel(如 ProfileViewModel、SettingsViewModel)。
  • 职责:
    • 基于用户动作或业务逻辑构造具体的 Notification 数据对象。
    • 持有对 NotificationSender(Invoker)的引用。
    • 调用 notificationSender.send() 发起请求。
    • 消费 Flow<Outcome> 以响应结果。

Invoker(调用者)

Invoker 持有命令并请求其执行,与动作本身完全解耦。

  • 实现: NotificationSender(接口)与 DefaultNotificationSender(具体类)。
  • 职责:
    • DefaultNotificationSender 实现 NotificationSender 接口。
    • 使用工厂获取正确的命令实例。
    • 对工厂返回的命令列表逐一调用 execute()。

从源码看,DefaultNotificationSender.send() 的流程(DefaultNotificationSender.kt):按通知类型构建命令列表——若 notification is SystemNotification 则追加 DisplaySystemNotificationCommand,若 notification is InAppNotification 则追加 DisplayInAppNotificationCommand;如果列表为空(例如通知既不是 System 也不是 InApp),则发射 CommandNotCreated 失败结果并记录 warn 日志。因此,一条同时实现两个接口的通知会依次生成并执行两条命令,分别投递到系统与应用内。

Command(命令)

Command 对象封装了执行所需的全部信息。

  • 实现: NotificationCommand(抽象基类,见 NotificationCommand.kt),具体类如 SystemNotificationCommand、InAppNotificationCommand。
  • 职责:
    • 绑定一个 Notification(负载)与一个 NotificationNotifier(接收者)。
    • 提供统一的 execute() 接口,Invoker 无需了解命令的具体细节即可调用。

Receiver(接收者)

Receiver 知道如何完成请求所需的工作,业务逻辑就在这里。

  • 实现: NotificationNotifier(接口),具体类如 SystemNotificationNotifier 与 InAppNotificationNotifier。
  • 职责:
    • 包含展示通知的平台特定实现。
    • SystemNotificationNotifier 使用 Android NotificationManager(AndroidSystemNotificationNotifier.kt)。
    • InAppNotificationNotifier 使用 InAppNotificationEventBus 通知应用有可用通知;InAppNotificationScaffold 监听该事件并展示通知(InAppNotificationNotifier.kt)。

命令模式实现均有对应单元测试覆盖,例如 DefaultNotificationSenderTest.kt、DisplaySystemNotificationCommandTest.kt、DisplayInAppNotificationCommandTest.kt 与 DefaultSystemNotificationStreamTest.kt,它们共同验证了命令分发、结果发射与事件流行为。

为什么这样设计?

  • 将请求与平台渲染解耦。
  • 支持单元测试与 fake 实现(feature/notification/testing 模块提供了 FakeNotificationSender、FakeSystemNotificationNotifier、FakeInAppNotificationNotifier、FakeNotificationManager 等测试替身,便于各 Feature 模块独立测试)。
  • 使新增 provider/样式变得直接简单。

附录:数据模型参考

Notification 为 sealed interface,禁止在包外直接实现,必须继承抽象类 AppNotification(AppNotification.kt)。其 accountUuid 为可空 String?,可用于按账户过滤要展示的通知。

classDiagram
    direction LR
    class Notification {
        <<interface>>
        + accountUuid: String?
        + title: String
        + contentText: String?
        + accessibilityText: String
        + severity: NotificationSeverity
        + createdAt: LocalDateTime
        + actions: Set~NotificationAction~
        + icon: NotificationIcon
    }
    class AppNotification {
        <<abstract>>
    }
    class SystemNotification {
        <<interface>>
        + subText: String?
        + channel: NotificationChannel
        + group: NotificationGroup?
        + systemNotificationStyle: SystemNotificationStyle
        + asLockscreenNotification(): LockscreenNotification?
    }
    class LockscreenNotification {
        <<data>>
        + notification: SystemNotification
        + lockscreenNotificationAppearance: LockscreenNotificationAppearance
    }
    class LockscreenNotificationAppearance {
        <<enum>>
        None
        AppName
        Public
        MessageCount
    }
    class InAppNotification {
        <<interface>>
        + inAppNotificationStyle: InAppNotificationStyle
    }
    class NotificationSeverity {
        <<enum>>
        Fatal
        Critical
        Temporary
        Warning
        Information
    }
    class NotificationAction {
        + icon: NotificationIcon?
        + title: String
    }
    class NotificationIcon {
        + systemNotificationIcon: SystemNotificationIcon?
        + inAppNotificationIcon: ImageVector?
    }
    class NotificationChannel {
        + id: String
        + name: StringResource
        + description: StringResource
        + importance: NotificationChannelImportance
    }
    class NotificationChannelImportance {
        <<enum>>
        None
        Min
        Low
        Default
        High
    }
    class SystemNotificationStyle {
        <<sealed>>
    }
    class BigTextStyle {
        + text: String
    }
    class InboxStyle {
        + bigContentTitle: String
        + summary: String
        + lines: List~CharSequence~
    }
    class SystemNotificationStyle.Undefined { }
    class InAppNotificationStyle { <<sealed>> }
    class InAppNotificationStyle.Undefined { }
    class SnackbarNotification { + duration: SnackbarDuration }
    class BannerGlobalNotification { }
    class BannerInlineNotification { }
    class DialogNotification { }

    Notification --> NotificationSeverity
    Notification --> NotificationAction
    Notification --> NotificationIcon
    Notification <|-- AppNotification
    Notification <|-- SystemNotification
    Notification <|-- InAppNotification
    SystemNotification --> SystemNotificationStyle
    SystemNotification --> NotificationChannel
    SystemNotification <--> LockscreenNotification
    NotificationChannel --> NotificationChannelImportance
    InAppNotification --> InAppNotificationStyle
    InAppNotification --> NotificationIcon
    SystemNotificationStyle <|-- SystemNotificationStyle.Undefined
    SystemNotificationStyle <|-- BigTextStyle
    SystemNotificationStyle <|-- InboxStyle
    InAppNotificationStyle <|-- InAppNotificationStyle.Undefined
    InAppNotificationStyle <|-- SnackbarNotification
    InAppNotificationStyle <|-- BannerGlobalNotification
    InAppNotificationStyle <|-- BannerInlineNotification
    InAppNotificationStyle <|-- DialogNotification

总结与最佳实践

  • 选择正确的类型:根据前台/后台时机选择 System/In-App;必要时两者都实现。
  • 始终设置严重级别:控制打扰程度与视觉提示。
  • 优先用工厂做本地化文本:KMP 代码中使用 suspend 工厂函数;Android-only 模块用注入 *ResourceManager 的工厂类。
  • 应用内屏幕:用 InAppNotificationScaffold 包裹内容并消费 PaddingValues。
  • 系统通知:先检查 POST_NOTIFICATIONS 权限,再展示;渠道选择直接影响通知的重要程度与用户控制。
  • 刻意使用样式:
    • BigText 用于内容丰富的单条更新;
    • Inbox 用于摘要/聚合;
    • Banner Global 用于持久全局警告;
    • Banner Inline 用于上下文阻塞提示;
    • Snackbar 用于瞬态反馈;
    • Dialog 用于必须行动(如请求通知权限)的提示。

在动手新增通知类型时,建议同时阅读 通知架构文档、通知样式文档 以及 feature/notification/api/src/commonMain/.../content/ 下的现成实现(如 AuthenticationErrorNotification.kt、CertificateErrorNotification.kt),它们是最佳的一手参考样例。

登录后查看全文
thunderbird-android