Firebase Cloud Messaging은 메시지를 여러 기기로 타겟팅하는 두 가지 방법을 제공합니다.
이 튜토리얼은 FCM용 Admin SDK 또는 REST API 를 사용하여 앱 서버에서 주제 메시지를 전송하고 Android 앱에서 수신 및 처리하는 방법에 중점을 둡니다. 백그라운드 및 포그라운드 앱 모두에 대한 메시지 처리를 다룰 것입니다. 설정에서 확인에 이르기까지 이를 달성하기 위한 모든 단계를 다룹니다.
SDK 설정
이 섹션에서는 FCM용 Android 클라이언트 앱을 설정 했거나 첫 번째 메시지 보내기 단계를 수행한 경우 이미 완료한 단계를 다룰 수 있습니다.
시작하기 전에
Android Studio 를 최신 버전으로 설치하거나 업데이트합니다.
프로젝트가 다음 요구 사항을 충족하는지 확인하십시오.
- API 레벨 19(KitKat) 이상 대상
- 안드로이드 4.4 이상 사용
- 다음 버전 요구 사항을 충족하는 Jetpack(AndroidX) 을 사용합니다.
-
com.android.tools.build:gradle
v3.2.1 이상 -
compileSdkVersion
28 이상
-
실제 기기를 설정하거나 에뮬레이터 를 사용하여 앱을 실행합니다.
Google Play 서비스에 종속된 Firebase SDK를 사용 하려면 기기나 에뮬레이터에 Google Play 서비스가 설치되어 있어야 합니다.Google 계정을 사용하여 Firebase에 로그인 합니다.
아직 Android 프로젝트가 없고 Firebase 제품을 사용해 보고 싶다면 빠른 시작 샘플 중 하나를 다운로드할 수 있습니다.
Firebase 프로젝트 만들기
Android 앱에 Firebase를 추가하려면 먼저 Android 앱에 연결할 Firebase 프로젝트를 만들어야 합니다. Firebase 프로젝트에 대해 자세히 알아보려면 Firebase 프로젝트 이해 를 방문하세요.
Firebase에 앱 등록
Android 앱에서 Firebase를 사용하려면 Firebase 프로젝트에 앱을 등록해야 합니다. 앱을 등록하는 것을 종종 프로젝트에 앱을 "추가"라고 합니다.
Firebase 콘솔 로 이동합니다.
프로젝트 개요 페이지 중앙에서 Android 아이콘(
) 또는 앱 추가 를 클릭하여 설정 워크플로를 시작합니다.Android 패키지 이름 필드에 앱의 패키지 이름을 입력합니다.
패키지 이름 은 기기와 Google Play 스토어에서 앱을 고유하게 식별합니다.
패키지 이름 은 종종 애플리케이션 ID 라고 합니다.
모듈(앱 수준) Gradle 파일(일반적으로
app/build.gradle
)에서 앱의 패키지 이름을 찾습니다(예: 패키지 이름:com.yourcompany.yourproject
).패키지 이름 값은 대소문자를 구분하며 Firebase 프로젝트에 등록한 후에는 이 Firebase Android 앱에 대해 변경할 수 없습니다.
(선택사항) 기타 앱 정보 입력: 앱 닉네임 및 디버그 서명 인증서 SHA-1 .
앱 닉네임 : Firebase 콘솔에서 나에게만 표시되는 내부 편의 식별자
디버그 서명 인증서 SHA-1 : SHA-1 해시 는 Firebase 인증( Google 로그인 또는 전화번호 로그인 사용 시 ) 및 Firebase 동적 링크 에 필요합니다.
앱 등록 을 클릭합니다.
Firebase 구성 파일 추가
Firebase Android 구성 파일(
)을 다운로드하여 앱에 추가합니다.google-services.json google-services.json 다운로드 를 클릭하여 Firebase Android 구성 파일을 가져옵니다.
구성 파일을 앱의 모듈(앱 수준) 루트 디렉터리로 이동합니다.
Firebase 구성 파일에는 고유하지만 비밀이 아닌 프로젝트 식별자가 포함되어 있습니다. 이 구성 파일에 대해 자세히 알아보려면 Firebase 프로젝트 이해 를 방문하세요.
언제든지 Firebase 구성 파일 을 다시 다운로드할 수 있습니다.
구성 파일 이름에
(2)
와 같은 추가 문자가 추가되지 않았는지 확인하십시오.
Firebase SDK에서
구성 파일의 값에 액세스할 수 있도록 하려면 Google 서비스 Gradle 플러그인 (google-services.json google-services
)이 필요합니다.루트 수준(프로젝트 수준) Gradle 파일(
<project>/build.gradle
)에서 Google 서비스 플러그인을 buildscript 종속성으로 추가합니다.buildscript { repositories { // Make sure that you have the following two repositories google() // Google's Maven repository mavenCentral() // Maven Central repository } dependencies { ... // Add the dependency for the Google services Gradle plugin classpath 'com.google.gms:google-services:4.3.15' } } allprojects { ... repositories { // Make sure that you have the following two repositories google() // Google's Maven repository mavenCentral() // Maven Central repository } }
모듈(앱 수준) Gradle 파일(일반적으로
<project>/<app-module>/build.gradle
)에서 Google 서비스 플러그인을 추가합니다.plugins { id 'com.android.application' // Add the Google services Gradle plugin id 'com.google.gms.google-services' ... }
앱에 Firebase SDK 추가
모듈(앱 수준) Gradle 파일 (일반적으로
<project>/<app-module>/build.gradle
)에서 Firebase Cloud Messaging Android 라이브러리에 대한 종속성을 추가합니다. Firebase Android BoM 을 사용하여 라이브러리 버전 관리를 제어하는 것이 좋습니다.Firebase 클라우드 메시징에 대한 최적의 환경을 위해 Firebase 프로젝트에서 Google Analytics를 활성화 하고 앱에 Google Analytics용 Firebase SDK를 추가하는 것이 좋습니다.
Java
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.0') // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-messaging' implementation 'com.google.firebase:firebase-analytics' }
Firebase Android BoM 을 사용하면 앱에서 항상 호환되는 버전의 Firebase Android 라이브러리를 사용합니다.
(대안) BoM을 사용 하지 않고 Firebase 라이브러리 종속성 추가
Firebase BoM을 사용하지 않기로 선택한 경우 종속성 줄에 각 Firebase 라이브러리 버전을 지정해야 합니다.
앱에서 여러 Firebase 라이브러리를 사용하는 경우 BoM을 사용하여 모든 버전이 호환되도록 라이브러리 버전을 관리하는 것이 좋습니다.
dependencies { // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-messaging:23.1.1' implementation 'com.google.firebase:firebase-analytics:21.2.0' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.0') // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries // When using the BoM, you don't specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-messaging-ktx' implementation 'com.google.firebase:firebase-analytics-ktx' }
Firebase Android BoM 을 사용하면 앱에서 항상 호환되는 버전의 Firebase Android 라이브러리를 사용합니다.
(대안) BoM을 사용 하지 않고 Firebase 라이브러리 종속성 추가
Firebase BoM을 사용하지 않기로 선택한 경우 종속성 줄에 각 Firebase 라이브러리 버전을 지정해야 합니다.
앱에서 여러 Firebase 라이브러리를 사용하는 경우 BoM을 사용하여 모든 버전이 호환되도록 라이브러리 버전을 관리하는 것이 좋습니다.
dependencies { // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation 'com.google.firebase:firebase-messaging-ktx:23.1.1' implementation 'com.google.firebase:firebase-analytics-ktx:21.2.0' }
Android 프로젝트를 Gradle 파일과 동기화합니다.
Android Gradle 플러그인(AGP) v4.2 이하를 사용하는 Gradle 빌드는 Java 8 지원을 활성화해야 합니다. 그렇지 않으면 Firebase SDK를 추가할 때 이러한 Android 프로젝트에 빌드 실패가 발생합니다.
이 빌드 실패를 수정하려면 다음 두 가지 옵션 중 하나를 따를 수 있습니다.
- 오류 메시지에 나열된
compileOptions
를 앱 수준build.gradle
파일에 추가합니다. - Android 프로젝트의
minSdkVersion
을 26 이상으로 늘립니다.
이 FAQ 에서 이 빌드 실패에 대해 자세히 알아보십시오.
- 오류 메시지에 나열된
주제에 대한 클라이언트 앱 구독
클라이언트 앱은 기존 주제를 구독하거나 새 주제를 생성할 수 있습니다. 클라이언트 앱이 새 주제 이름(Firebase 프로젝트에 아직 존재하지 않는 이름)을 구독하면 해당 이름의 새 주제가 FCM에 생성되고 이후에 모든 클라이언트가 이를 구독할 수 있습니다.
주제를 구독하기 위해 클라이언트 앱은 FCM 주제 이름으로 Firebase Cloud Messaging subscribeToTopic()
을 호출합니다. 이 메서드는 구독 성공 여부를 확인하기 위해 완료 리스너에서 사용할 수 있는 Task
를 반환합니다.
Kotlin+KTX
Firebase.messaging.subscribeToTopic("weather") .addOnCompleteListener { task -> var msg = "Subscribed" if (!task.isSuccessful) { msg = "Subscribe failed" } Log.d(TAG, msg) Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show() }
Java
FirebaseMessaging.getInstance().subscribeToTopic("weather") .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { String msg = "Subscribed"; if (!task.isSuccessful()) { msg = "Subscribe failed"; } Log.d(TAG, msg); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } });
구독을 취소하기 위해 클라이언트 앱은 주제 이름과 함께 Firebase Cloud Messaging unsubscribeFromTopic()
을 호출합니다.
주제 메시지 수신 및 처리
FCM은 다른 다운스트림 메시지와 동일한 방식으로 주제 메시지를 전달합니다.
메시지를 받으려면 FirebaseMessagingService 를 확장하는 서비스를 사용하세요. 서비스는 onMessageReceived
및 onDeletedMessages
콜백을 재정의해야 합니다. 수신 후 20초 이내에(Android Marshmallow의 경우 10초) 모든 메시지를 처리해야 합니다. 시간 창은 onMessageReceived
를 호출하기 전에 발생하는 OS 지연에 따라 더 짧아질 수 있습니다. 그 이후에는 Android O의 백그라운드 실행 제한 과 같은 다양한 OS 동작이 작업을 완료하는 데 방해가 될 수 있습니다. 자세한 내용은 메시지 우선 순위 에 대한 개요를 참조하십시오.
onMessageReceived
는 다음을 제외하고 대부분의 메시지 유형에 제공됩니다.
앱이 백그라운드에 있을 때 알림 메시지가 전달됩니다 . 이 경우 알림은 장치의 시스템 트레이로 전달됩니다. 사용자가 알림을 탭하면 기본적으로 앱 시작 관리자가 열립니다.
백그라운드에서 수신될 때 알림 및 데이터 페이로드가 모두 포함된 메시지 . 이 경우 알림은 장치의 시스템 트레이에 전달되고 데이터 페이로드는 런처 활동의 추가 의도로 전달됩니다.
요약하자면:
앱 상태 | 공고 | 데이터 | 둘 다 |
---|---|---|---|
전경 | onMessageReceived | onMessageReceived | onMessageReceived |
배경 | 시스템 트레이 | onMessageReceived | 알림: 시스템 트레이 데이터: 의도의 엑스트라. |
앱 매니페스트 편집
FirebaseMessagingService
를 사용하려면 앱 매니페스트에 다음을 추가해야 합니다.
<service android:name=".java.MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
또한 알림의 모양을 사용자 지정하려면 기본값을 설정하는 것이 좋습니다. 알림 페이로드에 동등한 값이 설정되지 않을 때마다 적용되는 사용자 정의 기본 아이콘 및 사용자 정의 기본 색상을 지정할 수 있습니다.
application
태그 안에 다음 줄을 추가하여 사용자 정의 기본 아이콘과 사용자 정의 색상을 설정합니다.
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages. See README(https://goo.gl/l4GJaQ) for more. --> <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_stat_ic_notification" /> <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming notification message. See README(https://goo.gl/6BKBk7) for more. --> <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/colorAccent" />
Android는 다음에 대한 맞춤 기본 아이콘을 표시합니다.
- 알림 작성기 에서 보낸 모든 알림 메시지입니다.
- 알림 페이로드에 아이콘을 명시적으로 설정하지 않은 모든 알림 메시지.
Android는 맞춤 기본 색상을 사용합니다.
- 알림 작성기 에서 보낸 모든 알림 메시지입니다.
- 알림 페이로드에서 색상을 명시적으로 설정하지 않은 모든 알림 메시지.
사용자 지정 기본 아이콘이 설정되지 않고 알림 페이로드에 아이콘이 설정되지 않은 경우 Android는 흰색으로 렌더링된 애플리케이션 아이콘을 표시합니다.
onMessageReceived
재정의
FirebaseMessagingService.onMessageReceived
메서드를 재정의하면 수신된 RemoteMessage 객체를 기반으로 작업을 수행하고 메시지 데이터를 가져올 수 있습니다.
Kotlin+KTX
override fun onMessageReceived(remoteMessage: RemoteMessage) { // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.d(TAG, "From: ${remoteMessage.from}") // Check if message contains a data payload. if (remoteMessage.data.isNotEmpty()) { Log.d(TAG, "Message data payload: ${remoteMessage.data}") if (/* Check if data needs to be processed by long running job */ true) { // For long-running tasks (10 seconds or more) use WorkManager. scheduleJob() } else { // Handle message within 10 seconds handleNow() } } // Check if message contains a notification payload. remoteMessage.notification?.let { Log.d(TAG, "Message Notification Body: ${it.body}") } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. }
Java
@Override public void onMessageReceived(RemoteMessage remoteMessage) { // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.d(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); if (/* Check if data needs to be processed by long running job */ true) { // For long-running tasks (10 seconds or more) use WorkManager. scheduleJob(); } else { // Handle message within 10 seconds handleNow(); } } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. }
onDeletedMessages
재정의
경우에 따라 FCM이 메시지를 전달하지 못할 수 있습니다. 연결 시 특정 기기에서 앱에 대해 대기 중인 메시지가 너무 많거나(>100) 기기가 한 달 이상 FCM에 연결되지 않은 경우에 발생합니다. 이 경우 FirebaseMessagingService.onDeletedMessages()
에 대한 콜백을 수신할 수 있습니다. 앱 인스턴스가 이 콜백을 수신하면 앱 서버와 전체 동기화를 수행해야 합니다. 지난 4주 동안 해당 기기의 앱에 메시지를 보내지 않은 경우 FCM은 onDeletedMessages()
를 호출하지 않습니다.백그라운드 앱에서 알림 메시지 처리
앱이 백그라운드에 있을 때 Android는 알림 메시지를 시스템 트레이로 보냅니다. 사용자가 알림을 탭하면 기본적으로 앱 시작 관리자가 열립니다.
여기에는 알림 및 데이터 페이로드(및 알림 콘솔에서 보낸 모든 메시지)가 모두 포함된 메시지가 포함됩니다. 이러한 경우 알림은 장치의 시스템 트레이에 전달되고 데이터 페이로드는 런처 활동의 추가 의도로 전달됩니다.
앱에 대한 메시지 전달에 대한 통찰력은 Android 앱에 대한 "노출"(사용자에게 표시되는 알림) 데이터와 함께 Apple 및 Android 기기에서 전송되고 열린 메시지 수를 기록하는 FCM 보고 대시보드 를 참조하십시오.
백그라운드 제한 앱(Android P 이상)
FCM은 사용자가 백그라운드 제한 으로 설정한 앱(예: 설정 -> 앱 및 알림 -> [앱 이름] -> 배터리)에 메시지를 전달하지 않을 수 있습니다. 앱이 백그라운드 제한에서 제거되면 이전과 같이 앱에 대한 새 메시지가 전달됩니다. 메시지 손실 및 기타 백그라운드 제한 영향을 방지하려면 Android vitals 노력에 나열된 나쁜 동작을 피해야 합니다. 이러한 동작으로 인해 Android 기기에서 사용자에게 앱이 백그라운드에서 제한되도록 권장할 수 있습니다. 앱은 isBackgroundRestricted() 를 사용하여 백그라운드가 제한된지 확인할 수 있습니다.보내기 요청 작성
주제를 생성한 후 클라이언트 측에서 주제에 대한 클라이언트 앱 인스턴스를 구독하거나 서버 API 를 통해 주제에 메시지를 보낼 수 있습니다. FCM에 대한 전송 요청을 처음 작성하는 경우 서버 환경 및 FCM 에 대한 가이드에서 중요한 배경 및 설정 정보를 참조하세요.
백엔드의 전송 논리에서 다음과 같이 원하는 주제 이름을 지정합니다.
Node.js
// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';
const message = {
data: {
score: '850',
time: '2:45'
},
topic: topic
};
// Send a message to devices subscribed to the provided topic.
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
자바
// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";
// See documentation on defining a message payload.
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setTopic(topic)
.build();
// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
파이썬
# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'
# See documentation on defining a message payload.
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
topic=topic,
)
# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
가다
// The topic name can be optionally prefixed with "/topics/".
topic := "highScores"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Topic: topic,
}
// Send a message to the devices subscribed to the provided topic.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
씨#
// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";
// See documentation on defining a message payload.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
Topic = topic,
};
// Send a message to the devices subscribed to the provided topic.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
쉬다
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"topic" : "foo-bar",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message"
}
}
}
cURL 명령:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message": {
"topic" : "foo-bar",
"notification": {
"body": "This is a Firebase Cloud Messaging Topic Message!",
"title": "FCM Message"
}
}
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
주제 조합 에 메시지를 보내려면 대상 주제를 지정하는 부울 표현식인 condition 을 지정합니다. 예를 들어 다음 조건은 TopicA
와 TopicB
또는 TopicC
를 구독하는 장치에 메시지를 보냅니다.
"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
FCM은 먼저 괄호 안의 조건을 평가한 다음 왼쪽에서 오른쪽으로 표현식을 평가합니다. 위 식에서 단일 주제를 구독하는 사용자는 메시지를 받지 않습니다. 마찬가지로 TopicA
를 구독하지 않는 사용자는 메시지를 받지 못합니다. 다음 조합은 수신합니다.
-
TopicA
및TopicB
-
TopicA
및TopicC
조건식에 최대 5개의 주제를 포함할 수 있습니다.
조건으로 보내려면:
Node.js
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics';
// See documentation on defining a message payload.
const message = {
notification: {
title: '$FooCorp up 1.43% on the day',
body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
},
condition: condition
};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
자바
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
Message message = Message.builder()
.setNotification(Notification.builder()
.setTitle("$GOOG up 1.43% on the day")
.setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
.build())
.setCondition(condition)
.build();
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
파이썬
# Define a condition which will send to devices which are subscribed
# to either the Google stock or the tech industry topics.
condition = "'stock-GOOG' in topics || 'industry-tech' in topics"
# See documentation on defining a message payload.
message = messaging.Message(
notification=messaging.Notification(
title='$GOOG up 1.43% on the day',
body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
),
condition=condition,
)
# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
가다
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
condition := "'stock-GOOG' in topics || 'industry-tech' in topics"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Condition: condition,
}
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
씨#
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
var message = new Message()
{
Notification = new Notification()
{
Title = "$GOOG up 1.43% on the day",
Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
},
Condition = condition,
};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
쉬다
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"condition": "'dogs' in topics || 'cats' in topics",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message",
}
}
}
cURL 명령:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"notification": {
"title": "FCM Message",
"body": "This is a Firebase Cloud Messaging Topic Message!",
},
"condition": "'dogs' in topics || 'cats' in topics"
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
다음 단계
- 서버를 사용하여 클라이언트 앱 인스턴스를 주제에 구독하고 다른 관리 작업을 수행할 수 있습니다. 서버에서 주제 구독 관리를 참조하십시오.
- 여러 장치로 보내는 다른 방법에 대해 자세히 알아보기 — 장치 그룹 메시징