백그라운드 앱에 테스트 메시지 보내기
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
FCM을 시작하기 위해 앱이 백그라운드 상태일 때 알림 작성기에서 개발 기기로 테스트 알림 메시지를 전송하는 가장 단순한 사용 사례부터 살펴보겠습니다.
이 페이지에서는 설정에서 검증까지 이 작업을 수행하는 모든 단계를 설명하며 FCM용 Fultter 앱을 설정했으면 일부 단계가 이미 완료된 상태일 수 있습니다.
FCM 플러그인 설치
아직 설치하지 않았으면 Flutter에 Firebase SDK를 설치하고 초기화합니다.
Flutter 프로젝트의 루트에서 다음 명령어를 실행하여 플러그인을 설치합니다.
flutter pub add firebase_messaging
완료되면 Flutter 애플리케이션을 다시 빌드합니다.
flutter run
등록 토큰 액세스
특정 기기로 메시지를 보내려면 기기의 등록 토큰을
알아야 합니다. 알림 콘솔의 필드에 토큰을 입력해야 이 튜토리얼을 마칠 수 있으므로 토큰을 검색한 후 복사하거나 안전하게 저장해야 합니다.
앱 인스턴스의 현재 등록 토큰을 가져오려면 getToken()
을 호출합니다. 알림 권한이 부여되지 않은 경우 이 메서드는 사용자에게 알림 권한을 요청합니다. 그렇지 않은 경우 토큰을 반환하거나 오류가 있으면 예정을 거부합니다.
final fcmToken = await FirebaseMessaging.instance.getToken();
테스트 알림 메시지 전송
대상 기기에 앱을 설치하고 실행합니다. Apple 기기에서는 원격 알림을 수신할 수 있는 권한 요청을 수락해야 합니다.
앱을 기기에서 백그라운드 상태로 만듭니다.
Firebase Console에서 메시지 페이지를 엽니다.
첫 번째 메시지인 경우 첫 번째 캠페인 만들기를 선택합니다.
- Firebase 알림 메시지를 선택하고 만들기를 선택합니다.
그렇지 않으면 캠페인 탭에서 새 캠페인을 선택한 후 알림을 선택합니다.
메시지 본문을 입력합니다. 다른 모든 필드는 선택사항입니다.
오른쪽 창에서 테스트 메시지 전송을 선택합니다.
FCM 등록 토큰 추가 필드에 이 가이드의 앞선 섹션에서 가져온 등록 토큰을 입력합니다.
테스트를 선택합니다.
테스트를 선택하면 타겟팅된 클라이언트 기기(앱은 백그라운드 상태임)에서 알림을 수신해야 합니다.
앱으로 전송된 메시지의 통계를 파악하려면 Apple 및 Android 기기에서 열린 전송 메시지 수와 Android 앱의 '노출수'(사용자에게 표시된 알림) 데이터가 기록된 FCM 보고 대시보드를 확인합니다.
상호작용 처리
사용자가 알림을 탭하면 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 앱에서 메시지 수신을 참조하여 포그라운드 앱에 전송하는 방법을 알아보세요.
알림 메시지 이외의 고급 기능
앱에 다른 고급 동작을 추가하려면 서버 구현이 필요합니다.
그런 다음 앱 클라이언트에서 다음을 수행합니다.
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-08-16(UTC)
[null,null,["최종 업데이트: 2025-08-16(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)"]]