FCM을 시작하기 위해 앱이 백그라운드 상태일 때 알림 작성기에서 개발 기기로 테스트 알림 메시지를 전송하는 가장 단순한 사용 사례부터 살펴보겠습니다.
이 페이지에서는 설정에서 검증까지 이 작업을 수행하는 모든 단계를 설명하며 FCM용 Fultter 앱을 설정했으면 일부 단계가 이미 완료된 상태일 수 있습니다.
테스트를 선택하면 타겟팅된 클라이언트 기기(앱은 백그라운드 상태임)에서 알림을 수신해야 합니다.
앱으로 전송된 메시지의 통계를 파악하려면 Apple 및 Android 기기에서 열린 전송 메시지 수와 Android 앱의 '노출수'(사용자에게 표시된 알림) 데이터가 기록된 FCM 보고 대시보드를 확인합니다.
상호작용 처리
사용자가 알림을 탭하면 Android 및 iOS의 기본 동작은 애플리케이션을 여는 것입니다. 애플리케이션이 종료된 상태라면 시작되고, 백그라운드에 있다면 포그라운드로 전환됩니다.
알림의 콘텐츠에 따라 애플리케이션이 열릴 때 사용자의 상호작용을 처리하려고 할 수 있습니다. 예를 들어 새 채팅 메시지가 알림을 통해 전송되고 사용자가 이를 선택하면 애플리케이션이 열릴 때 특정 대화를 열려고 할 수 있습니다.
firebase-messaging 패키지는 이 상호작용을 처리하는 두 가지 방법을 제공합니다.
getInitialMessage(): 애플리케이션이 종료된 상태에서 열리면 이 메서드는 RemoteMessage가 포함된 Future를 반환합니다. 소비되면 RemoteMessage가 삭제됩니다.
onMessageOpenedApp: 애플리케이션이 백그라운드 상태에서 열릴 때 RemoteMessage를 게시하는 Stream입니다.
사용자에게 원활한 환경을 보장하려면 두 시나리오를 모두 처리해야 합니다. 아래 코드 예시는 이를 처리하는 방법을 개략적으로 설명합니다.
classApplicationextendsStatefulWidget{@overrideState<StatefulWidget>createState()=>_Application();}class_ApplicationextendsState<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=awaitFirebaseMessaging.instance.getInitialMessage();// If the message also contains a data property with a "type" of "chat",// navigate to a chat screenif(initialMessage!=null){_handleMessage(initialMessage);}// Also handle any interaction when the app is in the background via a// Stream listenerFirebaseMessaging.onMessageOpenedApp.listen(_handleMessage);}void_handleMessage(RemoteMessagemessage){if(message.data['type']=='chat'){Navigator.pushNamed(context,'/chat',arguments:ChatArguments(message),);}}@overridevoidinitState(){super.initState();// Run code required to handle interacted messages in an async function// as initState() must not be asyncsetupInteractedMessage();}@overrideWidgetbuild(BuildContextcontext){returnText("...");}}
상호작용을 처리하는 방법은 애플리케이션 설정에 따라 다릅니다. 위의 예시는 StatefulWidget을 사용하는 기본 예시를 보여줍니다.
다음 단계
포그라운드 앱에 메시지 전송
백그라운드 앱에 알림 메시지를 보내는 데 성공했으면 Flutter 앱에서 메시지 수신을 참조하여 포그라운드 앱에 전송하는 방법을 알아보세요.
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[],[],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)"]]