使用 Firebase 云消息传递发送通知消息

17 Mar 2025 | 6 分钟阅读

在本节中,我们将讨论当应用在设备后台时,如何从通知编辑器向开发设备发送测试通知消息。为此,我们必须

1) 创建一个 Firebase 项目。

2) 从助手或控制台将我们的应用连接到 Firebase,并将 google-services.json 文件下载到我们的应用目录。

3) 在我们的项目级 build.gradle 文件中,确保在我们的 buildscript 和所有项目部分中都包含 Google 的 Maven 存储库。

Sending a Notification Message using Firebase Cloud Messaging

4) 对于应用 build.gradle 文件,我们有两个实现库"

  1. 将 Cloud Messaging Android 库和 firebase 核心库添加到我们的 app/build.gradle 文件
    1. 实现 'com.google.firebase:firebase-core:17.0.0'
    2. 实现 'com.google.firebase:firebase-messaging:19.0.1'
  2. 此外,添加 google play 依赖项(classpath 和 apply)
    1. apply plugin:'com.google.gms.google-services'
    2. classpath 'com.google.gms:google-services:4.2.0'
Sending a Notification Message using Firebase Cloud Messaging

5) 编辑我们的应用程序清单

建议并支持通知频道。 FCM 提供了具有基本设置的默认通知频道。如果我们想创建并使用我们的默认频道,那么我们必须将 default_notification_channel_id 设置为通知频道对象的 ID。当传入消息未明确设置通知频道时,FCM 将使用此值

6) 现在,我们将移至我们的主活动,以确保创建通知频道。

7) 访问设备注册令牌

在我们的应用初始启动时,FCM SDK 为客户端应用实例生成一个注册令牌。如果我们想定位单个设备,我们将需要通过扩展 FirebaseMessagingService 并重写 onNewToken 来访问此令牌。令牌可以在初始启动后轮换,因此强烈建议检索最新的更新注册令牌。

注册令牌可能会更改

  1. 当实例 ID 被应用程序删除时。
  2. 当应用程序在新的设备上恢复时。
  3. 当用户重新安装/卸载应用程序时。
  4. 当用户清除应用数据时。
  5. 检索当前注册令牌

当我们需要检索当前令牌时,调用 FirebaseIntanceId.getInstance().getInstanceId().4

9) 监视令牌生成

当生成新令牌时,将触发 oneNewToken 回调。当我们获得令牌时,我们可以将其发送到我们的应用服务器,并使用我们首选的方法存储它

activity_main.xml

Sending a Notification Message using Firebase Cloud Messaging

Main_activity.kt

MyFirebaseMessagingService.kt

Sending a Notification Message using Firebase Cloud Messaging Sending a Notification Message using Firebase Cloud Messaging

当我们单击“记录令牌”按钮时,它会为我们提供一个 InstanceID 令牌,我们在 FCM 控制台中用它来发送消息。

Sending a Notification Message using Firebase Cloud Messaging

现在,我们将移至我们的 FCM 控制台,然后单击 新建通知

Sending a Notification Message using Firebase Cloud Messaging

单击 新建通知 后,它将要求我们填写一些字段,例如通知标题、文本和图像等,然后单击 选择测试消息

Sending a Notification Message using Firebase Cloud Messaging

我们将复制的 InstanceId 令牌粘贴到 添加 FCM 注册令牌 字段中,然后单击 测试

Sending a Notification Message using Firebase Cloud Messaging

最后一步在我们的应用的通知栏中创建一个通知消息。只有当我们的应用程序在后台运行时,才会显示通知。

Sending a Notification Message using Firebase Cloud Messaging