如何在Kotlin中通过Firebase FCM设备Token向指定用户推送通知?
Kotlin + Firebase FCM: 按设备Token推送通知实现示例
下面是完整的可直接运行的代码示例,包含后端(Kotlin/JVM)发送通知和Android客户端接收通知的逻辑:
一、前置准备
后端(Kotlin/JVM)
- 从Firebase控制台下载服务账号密钥JSON文件,放在项目资源目录。
- 在
build.gradle.kts中添加Firebase Admin SDK依赖:
dependencies { implementation("com.google.firebase:firebase-admin:9.2.0") }
Android客户端
- 在Firebase控制台添加Android应用,下载
google-services.json放到app目录。 - 在
app/build.gradle.kts中添加FCM依赖:
dependencies { implementation("com.google.firebase:firebase-messaging-ktx:23.4.1") }
- 在
AndroidManifest.xml中注册自定义消息服务:
<service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
二、后端发送通知代码
用Firebase Admin SDK向指定设备Token推送通知:
import com.google.firebase.FirebaseApp import com.google.firebase.FirebaseOptions import com.google.firebase.messaging.FirebaseMessaging import com.google.firebase.messaging.Message import com.google.firebase.messaging.Notification import java.io.FileInputStream fun main() { // 初始化Firebase Admin SDK val serviceAccount = FileInputStream("path/to/your/serviceAccountKey.json") val options = FirebaseOptions.builder() .setCredentials(com.google.firebase.auth.FirebaseCredentials.fromStream(serviceAccount)) .build() FirebaseApp.initializeApp(options) // 替换为目标设备的Token val targetDeviceToken = "YOUR_DEVICE_TOKEN" // 构建通知内容 val notification = Notification.builder() .setTitle("FCM测试通知") .setBody("这是通过设备Token定向推送的消息") .build() // 构建消息(支持添加自定义数据) val message = Message.builder() .setToken(targetDeviceToken) .setNotification(notification) .putData("order_id", "12345") // 自定义数据,客户端可解析 .build() // 发送通知 try { val responseId = FirebaseMessaging.getInstance().send(message) println("通知发送成功,响应ID: $responseId") } catch (e: Exception) { println("发送失败:${e.localizedMessage}") } }
三、Android客户端接收通知代码
创建自定义MyFirebaseMessagingService处理消息接收和展示:
import com.google.firebase.messaging.FirebaseMessagingService import com.google.firebase.messaging.RemoteMessage import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.media.RingtoneManager import android.os.Build import androidx.core.app.NotificationCompat class MyFirebaseMessagingService : FirebaseMessagingService() { // 收到消息时触发 override fun onMessageReceived(remoteMessage: RemoteMessage) { // 处理通知内容 remoteMessage.notification?.let { showNotification(it.title ?: "新通知", it.body ?: "") } // 处理自定义数据 if (remoteMessage.data.isNotEmpty()) { println("收到自定义数据:${remoteMessage.data}") // 这里可以根据数据做业务逻辑处理,比如跳转对应页面 } } // 生成并显示系统通知 private fun showNotification(title: String, content: String) { // 点击通知跳转的页面 val intent = Intent(this, MainActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) } val pendingIntent = PendingIntent.getActivity( this, 0, intent, if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) PendingIntent.FLAG_IMMUTABLE else 0 ) val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION) val notificationBuilder = NotificationCompat.Builder(this, "FCM_CHANNEL_ID") .setSmallIcon(R.drawable.ic_notification) // 替换为你的通知图标 .setContentTitle(title) .setContentText(content) .setAutoCancel(true) .setSound(soundUri) .setContentIntent(pendingIntent) val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager // Android O及以上需要创建通知渠道 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = android.app.NotificationChannel( "FCM_CHANNEL_ID", "FCM通知渠道", NotificationManager.IMPORTANCE_DEFAULT ) notificationManager.createNotificationChannel(channel) } notificationManager.notify(0, notificationBuilder.build()) } // 获取新的设备Token(用于更新服务器存储的Token) override fun onNewToken(token: String) { println("新设备Token:$token") // 这里将Token发送到你的后端服务器保存 } }
四、测试流程
- 运行Android应用,在Logcat中找到
onNewToken打印的设备Token。 - 将Token替换到后端代码的
targetDeviceToken变量中。 - 运行后端代码,Android设备会立即收到通知。
内容的提问来源于stack exchange,提问作者Anand Nishad
相关产品推荐
相关产品推荐

