傳送測試訊息至背景執行的應用程式
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
如要開始使用 FCM,請先建構最簡單的用途:在應用程式於裝置上處於背景狀態時,從
通知撰寫器傳送測試通知訊息至開發裝置。本頁列出所有步驟,從設定到驗證都有,如果您已為 FCM 設定 Flutter 應用程式,可能已完成部分步驟。
安裝 FCM 外掛程式
如果尚未安裝並初始化 Flutter 適用的 Firebase SDK,請先完成這項操作。
在 Flutter 專案的根目錄中,執行下列指令來安裝外掛程式:
flutter pub add firebase_messaging
完成後,請重建 Flutter 應用程式:
flutter run
存取註冊權杖
如要傳送訊息給特定裝置,您必須知道該裝置的註冊權杖。您必須在「通知」控制台的欄位中輸入權杖,才能完成本教學課程,因此請務必在擷取權杖後複製或安全地儲存權杖。
如要擷取應用程式例項的目前註冊權杖,請呼叫 getToken()
。如果尚未授予通知權限,這個方法會要求使用者授予通知權限。否則,系統會傳回權杖,或因發生錯誤而拒絕 Future。
final fcmToken = await FirebaseMessaging.instance.getToken();
傳送測試通知訊息
在目標裝置上安裝並執行應用程式。在 Apple 裝置上,你必須接受接收遠端通知的權限要求。
確認裝置上的應用程式在背景執行。
在 Firebase 控制台中,開啟「訊息」頁面。
如果這是您的第一則訊息,請選取「建立您的第一個廣告活動」。
- 選取「Firebase 通知訊息」,然後選取「建立」。
否則,請在「廣告活動」分頁中選取「新增廣告活動」,然後選取「通知」。
輸入訊息文字。其他欄位則為選填。
在右側窗格中選取「傳送測試訊息」。
在標示為「新增 FCM 註冊權杖」的欄位中,輸入您在本指南先前章節中取得的註冊權杖。
選取「測試」。
選取「測試」後,目標用戶端裝置 (應用程式在背景執行) 應會收到通知。
如要深入瞭解訊息傳送至應用程式的情況,請參閱 FCM 報表資訊主頁,其中會記錄在 Apple 和 Android 裝置上傳送及開啟的訊息數量,以及 Android 應用程式的「曝光次數」資料 (使用者看到的通知)。
處理互動
使用者輕觸通知時,Android 和 iOS 預設都會開啟應用程式。如果應用程式已終止,系統會啟動應用程式;如果應用程式在背景執行,系統會將其移至前景。
視通知內容而定,您可能想在應用程式開啟時處理使用者的互動。舉例來說,如果使用者透過通知傳送新的即時通訊訊息並選取該訊息,您可能會想在應用程式開啟時開啟特定對話。
firebase-messaging
套件提供兩種處理這類互動的方式:
getInitialMessage()
:如果應用程式是從終止狀態開啟,這個方法會傳回包含 RemoteMessage
的 Future
。RemoteMessage
一經使用就會移除。
onMessageOpenedApp
:應用程式從背景狀態開啟時,會發布 RemoteMessage
的 Stream
。
為確保使用者體驗順暢,您應處理這兩種情況。以下程式碼範例說明如何達成這個目標:
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 應用程式中接收訊息」,開始傳送至前景應用程式。
不只是通知訊息
如要為應用程式新增其他進階行為,您需要伺服器實作。
接著,在應用程式用戶端中:
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2025-08-16 (世界標準時間)。
[null,null,["上次更新時間: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)"]]