向后台应用发送测试消息
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
开始使用 FCM 时,您可以构建一个最简单的用例:当应用在设备后台运行时,通过 Notifications Composer 向开发设备发送一条测试通知消息。
本页面列出了实现上述目标所需执行的步骤,包括从设置到验证的所有步骤。如果您已针对 FCM 设置了 Flutter 应用,您可能已经完成了本页面中的一些步骤。
安装 FCM 插件
安装并初始化适用于 Flutter 的 Firebase SDK(如果您尚未这样做)。
从 Flutter 项目的根目录运行以下命令,以安装该插件:
flutter pub add firebase_messaging
完成后,重新构建您的 Flutter 应用:
flutter run
获取注册令牌
如需将消息发送到特定的设备,您需要知道该设备的注册令牌。您需要在 Notifications 控制台的相应字段中输入该令牌才能完成本教程,因此请确保在获得令牌后即复制该令牌或将其妥善存储。
如需检索应用实例的当前注册令牌,请调用 getToken()
。如果未授予通知权限,此方法将向用户请求通知权限。在其他情况下,它会返回一个令牌,或由于出现错误而拒绝该 Future。
final fcmToken = await FirebaseMessaging.instance.getToken();
发送测试通知消息
在目标设备上安装并运行该应用。在 Apple 设备上,您需要接受权限请求,才能收到远程通知。
确保应用在设备的后台中运行。
在 Firebase 控制台中,打开“Messaging”(消息传递)页面。
如果这是您的第一条消息,请选择制作首个宣传活动。
- 选择 Firebase 通知消息,然后选择创建。
否则,请在宣传活动标签页上选择新建宣传活动,然后选择通知。
输入消息内容。所有其他字段都是选填字段。
从右侧窗格中选择发送测试消息。
在标签为添加 FCM 注册令牌的字段中,输入您根据本指南的前一部分获得的注册令牌。
选择测试。
在您选择测试后,目标客户端设备(在后台中运行应用)应该会接收到通知。
如需详细了解发送到您应用的消息,请参阅 FCM 报告信息中心。该信息中心会记录在 Apple 和 Android 设备上发送和打开的消息数量,以及 Android 应用的“展示次数”(用户看到的通知条数)数据。
处理交互
当用户点按通知时,Android 和 iOS 上的默认行为均是打开应用。也就是说,如果应用当前是终止状态,系统便会启动应用;如果应用在后台运行,系统则会将其转至前台。
根据通知的具体内容,您可能会希望在应用打开时便处理用户与通知的交互。例如,如果系统使用通知发送了新的聊天消息并且用户选择了该消息,那么您可能会希望应用在打开时便同时打开具体对话内容。
firebase-messaging
软件包提供了两种方式来处理此类交互:
getInitialMessage()
:如果应用在打开之前处于终止状态,则此方法会返回一个包含 RemoteMessage
的 Future
,并且系统会在用户使用该 RemoteMessage
之后将其移除。
onMessageOpenedApp
:如果应用在打开之前处于后台状态,则系统会通过一个 Stream
来发布 RemoteMessage
。
为了确保用户获得顺畅的体验,您应该处理这两种情况。以下代码示例简单展示了实现上述操作的方法:
class Application extends StatefulWidget {
@override
State<StatefulWidget> createState() => _Application();
}
class _Application extends State<Application> {
// In this example, suppose that all messages contain a data field with the key 'type'.
Future<void> setupInteractedMessage() async {
// Get any messages which caused the application to open from
// a terminated state.
RemoteMessage? initialMessage =
await FirebaseMessaging.instance.getInitialMessage();
// If the message also contains a data property with a "type" of "chat",
// navigate to a chat screen
if (initialMessage != null) {
_handleMessage(initialMessage);
}
// Also handle any interaction when the app is in the background via a
// Stream listener
FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);
}
void _handleMessage(RemoteMessage message) {
if (message.data['type'] == 'chat') {
Navigator.pushNamed(context, '/chat',
arguments: ChatArguments(message),
);
}
}
@override
void initState() {
super.initState();
// Run code required to handle interacted messages in an async function
// as initState() must not be async
setupInteractedMessage();
}
@override
Widget build(BuildContext context) {
return Text("...");
}
}
具体使用哪一种交互处理方式取决于您的应用设置。上面的示例展示了一个使用 StatefulWidget
的基本示例。
后续步骤
向前台应用发送消息
向在后台运行的应用成功发送通知消息后,您可参阅在 Flutter 应用中接收消息,尝试向前台应用发送消息。
除通知消息之外的其他功能
如需向您的应用添加其他更高级的行为,您需要服务器实现。
然后,在您的应用客户端中:
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-16。
[null,null,["最后更新时间 (UTC):2025-08-16。"],[],[],null,["\u003cbr /\u003e\n\nTo get started with FCM, build out the simplest use case: sending a\ntest notification message from the\n[Notifications composer](//console.firebase.google.com/project/_/notification) to a development device\nwhen the app is in the background on the device.\nThis page lists all the steps to achieve this, from setup to verification\n--- it may cover steps you already completed if you\nhave [set up a Flutter app](/docs/cloud-messaging/flutter/client)\nfor FCM.\n| **Important:** This guide focuses on the background case. If you want to receive messages when your app is in the foreground as well, see also [Receive Messages in a Flutter App](/docs/cloud-messaging/flutter/receive).\n\nInstall the FCM plugin\n\n1. [Install and initialize the Firebase SDKs for Flutter](/docs/flutter/setup)\n if you haven't already done so.\n\n2. From the root of your Flutter project, run the following command to install\n the plugin:\n\n flutter pub add firebase_messaging\n\n3. Once complete, rebuild your Flutter application:\n\n flutter run\n\nAccess the registration token\n\nTo send a message to a specific device, you need to know that device's\nregistration token. Because you'll need to enter the token in a field in the\nNotifications console to complete this tutorial, make sure to copy the token\nor securely store it after you retrieve it.\n\nTo retrieve the current registration token for an app instance, call\n`getToken()`. If notification permission has not been granted, this method will\nask the user for notification permissions. Otherwise, it returns a token or\nrejects the future due to an error. \n\n final fcmToken = await FirebaseMessaging.instance.getToken();\n\nSend a test notification message\n\n1. Install and run the app on the target device. On Apple devices, you'll need\n to accept the request for permission to receive remote notifications.\n\n2. Make sure the app is in the background on the device.\n\n3. In the Firebase console, open the [Messaging page](https://console.firebase.google.com/project/_/messaging/).\n\n4. If this is your first message, select **Create your first\n campaign**.\n\n 1. Select **Firebase Notification messages** and select **Create**.\n5. Otherwise, on the **Campaigns** tab, select **New campaign**\n and then **Notifications**.\n\n6. Enter the message text. All other fields are optional.\n\n7. Select **Send test message** from the right pane.\n\n8. In the field labeled **Add an FCM registration token**, enter the registration\n token you obtained in a previous section of this guide.\n\n9. Select **Test**.\n\nAfter you select **Test**, the targeted client device (with the app in\nthe background) should receive the notification.\n\nFor insight into message delivery to your app, see the\n[FCM reporting dashboard](//console.firebase.google.com/project/_/notification/reporting),\nwhich records the number of messages sent and opened on Apple and Android\ndevices, along with data for \"impressions\" (notifications seen by users) for\nAndroid apps.\n\nHandling interaction\n\nWhen users tap a notification, the default behavior on both Android \\& iOS is to open the application. If the application is terminated,\nit will be started, and if it is in the background, it will be brought to the foreground.\n\nDepending on the content of a notification, you may want to handle the user's interaction when the application\nopens. For example, if a new chat message is sent using a notification and the user selects it, you may want to\nopen the specific conversation when the application opens.\n\nThe `firebase-messaging` package provides two ways to handle this interaction:\n\n1. `getInitialMessage()`: If the application is opened from a terminated state, this method returns a `Future` containing a `RemoteMessage`. Once consumed, the `RemoteMessage` will be removed.\n2. `onMessageOpenedApp`: A `Stream` which posts a `RemoteMessage` when the application is opened from a background state.\n\nTo ensure a smooth experience for your users, you should handle both scenarios. The code example\nbelow outlines how this can be achieved: \n\n class Application extends StatefulWidget {\n @override\n State\u003cStatefulWidget\u003e createState() =\u003e _Application();\n }\n\n class _Application extends State\u003cApplication\u003e {\n // In this example, suppose that all messages contain a data field with the key 'type'.\n Future\u003cvoid\u003e setupInteractedMessage() async {\n // Get any messages which caused the application to open from\n // a terminated state.\n RemoteMessage? initialMessage =\n await FirebaseMessaging.instance.getInitialMessage();\n\n // If the message also contains a data property with a \"type\" of \"chat\",\n // navigate to a chat screen\n if (initialMessage != null) {\n _handleMessage(initialMessage);\n }\n\n // Also handle any interaction when the app is in the background via a\n // Stream listener\n FirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);\n }\n\n void _handleMessage(RemoteMessage message) {\n if (message.data['type'] == 'chat') {\n Navigator.pushNamed(context, '/chat',\n arguments: ChatArguments(message),\n );\n }\n }\n\n @override\n void initState() {\n super.initState();\n\n // Run code required to handle interacted messages in an async function\n // as initState() must not be async\n setupInteractedMessage();\n }\n\n @override\n Widget build(BuildContext context) {\n return Text(\"...\");\n }\n }\n\nHow you handle interaction depends on your application setup. The example above\nshows a basic example of using a `StatefulWidget`.\n\nNext steps\n\nSend messages to foregrounded apps\n\nOnce you have successfully sent notification messages while your app is in\nthe background, see\n[Receive Messages in a Flutter App](/docs/cloud-messaging/flutter/receive)\nto get started sending to foregrounded apps.\n\nGo beyond notification messages\n\nTo add other, more advanced behavior to your app, you'll need a\n[server implementation](/docs/cloud-messaging/server).\n\nThen, in your app client:\n\n- [Receive messages](/docs/cloud-messaging/flutter/receive)\n- [Subscribe to message topics](/docs/cloud-messaging/flutter/topic-messaging)"]]