推送通知
远程推送通知是应用与用户沟通的重要渠道。本文展示如何集成 FCM 和 APNs。
平台差异对比
| 平台 | 推送服务 | Token 管理 | 权限要求 |
|---|---|---|---|
| Android | FCM | FirebaseMessaging.getToken() | POST_NOTIFICATIONS (API 33+) |
| iOS | APNs | Device Token | 系统自动请求 |
| Desktop | - | 无标准支持 | - |
标准代码块
kotlin
expect object PushNotificationManager {
suspend fun getToken(): String?
fun onTokenRefresh(callback: (String) -> Unit)
fun onMessageReceived(callback: (Map<String, String>) -> Unit)
}kotlin
import com.google.firebase.messaging.FirebaseMessaging
import kotlinx.coroutines.tasks.await
actual object PushNotificationManager {
actual suspend fun getToken(): String? {
return try {
FirebaseMessaging.getInstance().token.await()
} catch (e: Exception) {
null
}
}
actual fun onTokenRefresh(callback: (String) -> Unit) {
// 在 FirebaseMessagingService 中实现
}
actual fun onMessageReceived(callback: (Map<String, String>) -> Unit) {
// 在 FirebaseMessagingService 中实现
}
}kotlin
import platform.UserNotifications.*
actual object PushNotificationManager {
actual suspend fun getToken(): String? {
// iOS 需要在启动时注册 APNs
return null
}
actual fun onTokenRefresh(callback: (String) -> Unit) {
// 在 AppDelegate 中实现
}
actual fun onMessageReceived(callback: (Map<String, String>) -> Unit) {
// 在 AppDelegate 中实现
}
}依赖补充
Android FCM
kotlin
dependencies {
implementation(platform("com.google.firebase:firebase-bom:32.7.0"))
implementation("com.google.firebase:firebase-messaging-ktx")
}