Skip to content

通知与推送通道 ​

一句话:Android 通知是双层模型——本地的"显示通知"靠 NotificationManager + Channel,远端推送靠 FCM(国际)/ 厂商通道(国内)。Channel 是 API 26+ 起的强制门槛,没 channel 不能发通知。


一、Android 通知的世界观 ​

通知有两种触发源:

来源谁触发用什么
本地通知你的 App 自己NotificationManager.notify(...)
推送通知远端服务器FCM(Google)/ 国内厂商(华米 OV)/ 自家长连接

两者最终都走相同的"在系统通知栏显示"路径,只是触发源不同。

Channel(API 26+ 强制) 是通知必须挂的"频道":每个 channel 独立配置重要性、声音、震动、显示样式。没 channel 不能发通知——这是 Android 强制让 App 给用户提供"按频道关闭通知"的细粒度控制。


二、NotificationChannel:必经的第一步 ​

kotlin
// 在 Application.onCreate 创建,只创建一次
class NotedXApp : Application() {
    override fun onCreate() {
        super.onCreate()
        createNotificationChannels()
    }

    private fun createNotificationChannels() {
        val manager = getSystemService<NotificationManager>()!!
        manager.createNotificationChannels(listOf(
            NotificationChannel(
                CHANNEL_SYNC, "同步状态", NotificationManager.IMPORTANCE_LOW
            ).apply {
                description = "后台同步进度与结果通知"
            },
            NotificationChannel(
                CHANNEL_REMINDER, "笔记提醒", NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = "笔记设置的时间提醒"
                enableVibration(true)
                enableLights(true)
            },
            NotificationChannel(
                CHANNEL_PUSH, "新内容推送", NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = "云端有新内容时的通知"
            },
        ))
    }

    companion object {
        const val CHANNEL_SYNC = "channel_sync"
        const val CHANNEL_REMINDER = "channel_reminder"
        const val CHANNEL_PUSH = "channel_push"
    }
}

Channel 设计原则:

  1. 按"用户感知的不同"分类——不要把"系统状态" / "用户消息" / "营销" 混在一个 channel
  2. IMPORTANCE_* 决定打扰强度:MIN(不显示)/ LOW(无声音)/ DEFAULT / HIGH(横幅 + 声音)/ MAX(全屏)
  3. Channel 创建后用户可以改但你不能改——创建时填 IMPORTANCE 就是默认值,之后用户在系统设置里调整,你的 API 调用无效

三、发本地通知的标准模式 ​

kotlin
fun showSyncCompleteNotification(ctx: Context, count: Int) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        if (ContextCompat.checkSelfPermission(ctx, Manifest.permission.POST_NOTIFICATIONS)
            != PackageManager.PERMISSION_GRANTED) return     // 没权限直接退出
    }

    val intent = Intent(ctx, MainActivity::class.java).apply {
        flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
        putExtra("route", "home")
    }
    val pendingIntent = PendingIntent.getActivity(
        ctx, 0, intent,
        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )

    val notification = NotificationCompat.Builder(ctx, NotedXApp.CHANNEL_SYNC)
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle("同步完成")
        .setContentText("更新了 $count 篇笔记")
        .setContentIntent(pendingIntent)
        .setAutoCancel(true)
        .setPriority(NotificationCompat.PRIORITY_LOW)
        .build()

    NotificationManagerCompat.from(ctx).notify(NOTIF_ID_SYNC, notification)
}

几个铁律:

  1. API 33+ 必须 POST_NOTIFICATIONS 权限——发通知前检查(15 篇)
  2. PendingIntent.FLAG_IMMUTABLE 必填(API 31+)——否则崩
  3. NotificationManagerCompat 而不是 NotificationManager——兼容老 API
  4. setSmallIcon——APK 体积优化:用单色矢量图(<vector>),系统会自动按主题色染色
  5. 通知 ID 全局唯一——同 ID 再 notify 会替换原通知(进度条用得着);不同 ID 多条独立

四、丰富通知:Big text / Big picture / Inbox ​

kotlin
NotificationCompat.Builder(ctx, CHANNEL_PUSH)
    .setSmallIcon(...)
    .setContentTitle("新评论")
    .setContentText(comment.preview)
    .setStyle(NotificationCompat.BigTextStyle().bigText(comment.fullText))  // 长文本展开
    // 或 BigPictureStyle / InboxStyle / MessagingStyle
    .setContentIntent(pendingIntent)
    .build()

MessagingStyle 是聊天 App 的标准——会显示对话气泡:

kotlin
NotificationCompat.MessagingStyle(Person.Builder().setName("我").build())
    .addMessage(NotificationCompat.MessagingStyle.Message("hi", timestamp, alicePerson))
    .addMessage(NotificationCompat.MessagingStyle.Message("hey", timestamp + 1000, mePerson))

五、通知 Action:不打开 App 就能操作 ​

kotlin
val replyIntent = PendingIntent.getBroadcast(ctx, 0,
    Intent(ctx, ReplyReceiver::class.java),
    PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)

NotificationCompat.Builder(...)
    .addAction(
        R.drawable.ic_reply,
        "回复",
        replyIntent,
    )
    .addAction(
        R.drawable.ic_delete,
        "删除",
        deleteIntent,
    )

注意:Action 的 PendingIntent 触发 BroadcastReceiver / Service 来处理——避免在用户点 Action 时打开 Activity(打断用户)。NotedX 的"标记已读"按钮就是这种。


六、通知进度:正在下载 ​

kotlin
val builder = NotificationCompat.Builder(ctx, CHANNEL_SYNC)
    .setSmallIcon(R.drawable.ic_sync)
    .setContentTitle("同步中")
    .setProgress(100, 0, false)      // max=100, current=0, indeterminate=false
    .setOngoing(true)                 // 不能划掉
    .setPriority(NotificationCompat.PRIORITY_LOW)

NotificationManagerCompat.from(ctx).notify(NOTIF_ID_SYNC, builder.build())

// 更新进度
fun updateProgress(progress: Int) {
    builder.setProgress(100, progress, false)
        .setContentText("已同步 $progress%")
    NotificationManagerCompat.from(ctx).notify(NOTIF_ID_SYNC, builder.build())
}

// 完成
fun showDone() {
    builder.setProgress(0, 0, false)
        .setContentText("同步完成")
        .setOngoing(false)
        .setAutoCancel(true)
    NotificationManagerCompat.from(ctx).notify(NOTIF_ID_SYNC, builder.build())
}

同 ID 反复 notify 就是更新——这是进度条通知的标准做法。


七、通知点击 → 路由到具体屏幕 ​

通知一般要"点进去到某个特定屏幕"(详情 / 列表 / 设置)。模式:

kotlin
val deepLinkIntent = Intent(
    Intent.ACTION_VIEW,
    "notedx://detail/$noteId".toUri(),
    ctx,
    MainActivity::class.java,
)

val pendingIntent = androidx.core.app.TaskStackBuilder.create(ctx).run {
    addNextIntentWithParentStack(deepLinkIntent)
    getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
}

TaskStackBuilder 会构造完整的 back stack——从详情按 back 能回到首页,而不是直接退出 App。

MainActivity 在 onNewIntent 接收 deep link,转发给 Navigation:

kotlin
override fun onNewIntent(intent: Intent) {
    super.onNewIntent(intent)
    setIntent(intent)
    navController.handleDeepLink(intent)    // Navigation Compose 2.8+ 自动解析
}

Navigation 配置里给目的地加 deep link(11 篇):

kotlin
composable<Route.Detail>(
    deepLinks = listOf(navDeepLink<Route.Detail>(basePath = "notedx://detail")),
) { ... }

八、FCM:Firebase Cloud Messaging(国际推送) ​

FCM 是 Google 提供的免费推送通道。国际版 NotedX 用 FCM;国内由于 Google Services 不可达,需要厂商通道(后面讲)。

接入步骤:

  1. Firebase Console 创建项目,下载 google-services.json 放 :app/

  2. 配置 Gradle:

    kotlin
    // 根 build.gradle.kts
    plugins {
        id("com.google.gms.google-services") version "4.4.2" apply false
    }
    // :app/build.gradle.kts
    plugins {
        id("com.google.gms.google-services")
    }
    dependencies {
        implementation(platform("com.google.firebase:firebase-bom:33.5.1"))
        implementation("com.google.firebase:firebase-messaging-ktx")
    }
  3. 创建 FirebaseMessagingService:

kotlin
@AndroidEntryPoint
class NotedXMessagingService : FirebaseMessagingService() {

    @Inject lateinit var tokenRepository: PushTokenRepository

    override fun onNewToken(token: String) {
        // 新 token,上报到 server
        CoroutineScope(SupervisorJob() + Dispatchers.IO).launch {
            tokenRepository.uploadToken(token)
        }
    }

    override fun onMessageReceived(message: RemoteMessage) {
        val title = message.notification?.title ?: message.data["title"] ?: return
        val body = message.notification?.body ?: message.data["body"] ?: ""
        val noteId = message.data["noteId"]?.toLongOrNull()
        showNotification(this, title, body, noteId)
    }
}
  1. manifest 注册:
xml
<service
    android:name=".push.NotedXMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
  1. server 端用 Firebase Admin SDK 发推:
bash
POST https://fcm.googleapis.com/v1/projects/{projectId}/messages:send
{
  "message": {
    "token": "<device_token>",
    "notification": { "title": "新评论", "body": "..." },
    "data": { "noteId": "42" }
  }
}

九、Notification vs Data Payload:两种 FCM 消息 ​

jsonc
// 1. notification payload(系统直接显示通知,App 在前台才走 onMessageReceived)
{ "notification": { "title": "...", "body": "..." } }

// 2. data payload(永远走 onMessageReceived,你自己决定显不显示)
{ "data": { "title": "...", "body": "...", "noteId": "42" } }

实操推荐永远用 data payload——更可控:可以在客户端决定是否显示通知、如何样式、如何 deeplink。notification payload 在 App 后台时系统直接显示,你拦不住。


十、国内推送通道:厂商通知 ​

Google Play Services 在国内大部分场景不可用,FCM 不能用。国内主流方案:统一推送联盟(UPN) + 各家厂商通道。

主流厂商通道:

厂商SDK主要机型
小米MiPush小米 / Redmi
华为HMS Push华为 / 荣耀
OPPOOPushOPPO 系
vivovPushvivo 系
魅族MzPush魅族
三星(走 FCM)三星
其他自家长连接 / 极光 / 个推兜底

对接复杂度:每家 SDK 自己一套 token / 注册 / 回调,接 5 家就是 5 倍工作。实操推荐用聚合方案:

  • 极光推送(JPush)——商业方案,内置多通道,代码统一
  • 个推 GTPush——同类商业方案
  • 腾讯 TPNS——腾讯系
  • 华为 HMS Push——已对接其他厂商通道,可以作为聚合

NotedX 国内版选极光或TPNS简化接入。

接入步骤(以 JPush 为例,简化):

kotlin
// Application.onCreate
JCollectionAuth.setAuth(this, true)
JPushInterface.setDebugMode(BuildConfig.DEBUG)
JPushInterface.init(this)

// 拿到 registrationID 上报 server
val regId = JPushInterface.getRegistrationID(this)

server 端用 JPush Server SDK 发推。

架构:抽象一个 PushProvider 接口,国际版注入 FCM 实现,国内版注入 JPush 实现:

kotlin
interface PushProvider {
    suspend fun initialize()
    suspend fun currentToken(): String?
    val tokenFlow: Flow<String>
}

@Module @InstallIn(SingletonComponent::class)
abstract class PushModule {
    @Binds @Singleton
    abstract fun bindProvider(impl: FcmPushProvider): PushProvider     // 或 JPushProvider
}

通过 Build Variant(gms / noGms)选择不同实现。


十一、通知与权限合并流程 ​

kotlin
@Composable
fun NotificationOnboarding(onComplete: () -> Unit) {
    val ctx = LocalContext.current
    val launcher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestPermission(),
        onResult = { onComplete() }
    )
    Column {
        Text("启用通知")
        Text("接收同步完成、评论提醒等消息")
        Button(onClick = {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                launcher.launch(Manifest.permission.POST_NOTIFICATIONS)
            } else {
                onComplete()
            }
        }) { Text("启用") }
        TextButton(onClick = onComplete) { Text("跳过") }
    }
}

何时启用通知:第一次用户进入"提醒"或"评论通知"功能时——而不是 App 一启动就弹。


十二、调试:adb 触发 / 检查 ​

bash
# 模拟 FCM 推送(只在 debug Build,需 push.json 文件)
adb shell am broadcast \
  -n com.notedx/com.google.firebase.iid.FirebaseInstanceIdReceiver \
  -a com.google.android.c2dm.intent.RECEIVE \
  --es message_id "0:1234" \
  --es from "/topics/test"

# 列出当前通知
adb shell dumpsys notification | grep com.notedx

# 测试 deep link
adb shell am start -a android.intent.action.VIEW -d "notedx://detail/42"

十三、踩坑 ​

坑 1:Android 13+ 不申请 POST_NOTIFICATIONS 直接 notify。系统会静默忽略,你以为发了实际没显示。永远先权限再 notify。

坑 2:PendingIntent 没加 FLAG_IMMUTABLE。API 31+ 强制要求,不加直接抛 IllegalArgumentException。

坑 3:Channel 创建后改 importance 没用。Channel importance 用户能在系统设置改,你的代码再 createChannel 重复设置无效(不允许调高强度)。要"重要性升级"只能删除 channel 再用新 ID 创建。

坑 4:通知图标(setSmallIcon)用彩色 PNG。系统会把它转黑白,显示很丑。必须用单色 vector(矢量 + 单色),系统按主题色染色。Android Studio 模板已经给了 ic_launcher_foreground 风格的 vector。

坑 5:通知 ID 重复。同一个 ID 后发的覆盖前发的——意外覆盖会让用户错过消息。每条独立通知用不同 ID(用 noteId / messageId 当 ID);唯一进度通知用固定 ID(故意覆盖)。

坑 6:点击通知打开 Activity 不带 deep link。点开后就是首页,用户找不到对应的笔记。永远用 TaskStackBuilder 构造完整 back stack 到目标屏幕。

坑 7:MessagingStyle 不用 Person。MessagingStyle.Message(text, time, person) 第三参数早期是 CharSequence,新 API 要 Person——不传 Person,通知样式降级到普通文本。

坑 8:国内市场把 FCM 用上。国内大部分手机没 GMS,FCM 收不到。国内 build 应当走厂商通道或聚合 SDK。

坑 9:推送 token 不上报 server。Token 是 server 找到这台设备的唯一标识。onNewToken 必须把新 token 上报——但服务器要"无 token 重复上报"幂等处理,因为用户登录 / 重装 / 切设备会反复变。

坑 10:在主线程做长任务。onMessageReceived 跑在工作线程没问题,但 BroadcastReceiver.onReceive 跑主线程——10 秒不退就 ANR。复杂处理走 WorkManager。


下一篇 18-CameraX与PhotoPicker.md,讲 Android 媒体能力:用 CameraX 拍照(代码量比 Camera2 减半)、用 Photo Picker 无权限选图、用 MediaStore 写入用户相册。NotedX 的"为笔记加图片附件"完整闭环。