基於發布/訂閱模型,FCM 主題訊息傳遞可讓您向選擇加入特定主題的多個裝置發送訊息。您根據需要撰寫主題訊息,FCM 負責路由並將訊息可靠地傳遞到正確的裝置。
例如,本地潮汐預報應用程式的使用者可以選擇「潮流警報」主題,並接收指定區域最佳鹹水捕魚條件的通知。體育應用程式的用戶可以訂閱他們最喜歡的球隊的即時比賽比分的自動更新。
關於主題需要記住的一些事項:
- 主題訊息最適合天氣或其他公開資訊等內容。
- 主題訊息針對吞吐量而不是延遲進行了最佳化。為了快速、安全地傳遞到單一裝置或小型裝置群組,請將訊息定位到註冊令牌,而不是主題。
- 如果您需要向每個使用者的多個裝置發送訊息,請考慮針對這些用例的裝置群組訊息傳遞。
- 主題訊息支持每個主題的無限訂閱。然而,FCM 在這些領域實施限制:
- 一個應用實例最多可以訂閱2000個主題。
- 如果您使用批次匯入來訂閱應用程式實例,則每個請求僅限於 1000 個應用程式實例。
- 每個項目的新訂閱頻率受到速率限制。如果您在短時間內發送太多訂閱請求,FCM 伺服器將回應
429 RESOURCE_EXHAUSTED
(「超出配額」)回應。使用指數退避重試。
為客戶端應用程式訂閱主題
客戶端應用程式可以訂閱任何現有主題,也可以建立新主題。當用戶端套用訂閱新的主題名稱(您的 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()
。
管理伺服器上的主題訂閱
Firebase Admin SDK可讓您從伺服器端執行基本的主題管理任務。給定他們的註冊令牌,您可以使用伺服器邏輯批量訂閱和取消訂閱客戶端應用程式實例。
您可以將客戶端應用程式實例訂閱到任何現有主題,也可以建立新主題。當您使用 API 為用戶端套用訂閱新主題(您的 Firebase 專案尚不存在的主題)時,FCM 中會建立一個同名的新主題,任何客戶端都可以隨後訂閱該主題。
您可以將註冊令牌清單傳遞給 Firebase Admin SDK 訂閱方法,以將相應的裝置訂閱主題:
Node.js
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// ...
'YOUR_REGISTRATION_TOKEN_n'
];
// Subscribe the devices corresponding to the registration tokens to the
// topic.
getMessaging().subscribeToTopic(registrationTokens, topic)
.then((response) => {
// See the MessagingTopicManagementResponse reference documentation
// for the contents of response.
console.log('Successfully subscribed to topic:', response);
})
.catch((error) => {
console.log('Error subscribing to topic:', error);
});
爪哇
// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n"
);
// Subscribe the devices corresponding to the registration tokens to the
// topic.
TopicManagementResponse response = FirebaseMessaging.getInstance().subscribeToTopic(
registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " tokens were subscribed successfully");
Python
# These registration tokens come from the client FCM SDKs.
registration_tokens = [
'YOUR_REGISTRATION_TOKEN_1',
# ...
'YOUR_REGISTRATION_TOKEN_n',
]
# Subscribe the devices corresponding to the registration tokens to the
# topic.
response = messaging.subscribe_to_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were subscribed successfully')
去
// These registration tokens come from the client FCM SDKs.
registrationTokens := []string{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
}
// Subscribe the devices corresponding to the registration tokens to the
// topic.
response, err := client.SubscribeToTopic(ctx, registrationTokens, topic)
if err != nil {
log.Fatalln(err)
}
// See the TopicManagementResponse reference documentation
// for the contents of response.
fmt.Println(response.SuccessCount, "tokens were subscribed successfully")
C#
// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
};
// Subscribe the devices corresponding to the registration tokens to the
// topic
var response = await FirebaseMessaging.DefaultInstance.SubscribeToTopicAsync(
registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} tokens were subscribed successfully");
管理 FCM API 還允許您透過將註冊令牌傳遞給適當的方法來取消訂閱裝置的主題:
Node.js
// These registration tokens come from the client FCM SDKs.
const registrationTokens = [
'YOUR_REGISTRATION_TOKEN_1',
// ...
'YOUR_REGISTRATION_TOKEN_n'
];
// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
getMessaging().unsubscribeFromTopic(registrationTokens, topic)
.then((response) => {
// See the MessagingTopicManagementResponse reference documentation
// for the contents of response.
console.log('Successfully unsubscribed from topic:', response);
})
.catch((error) => {
console.log('Error unsubscribing from topic:', error);
});
爪哇
// These registration tokens come from the client FCM SDKs.
List<String> registrationTokens = Arrays.asList(
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n"
);
// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
TopicManagementResponse response = FirebaseMessaging.getInstance().unsubscribeFromTopic(
registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
System.out.println(response.getSuccessCount() + " tokens were unsubscribed successfully");
Python
# These registration tokens come from the client FCM SDKs.
registration_tokens = [
'YOUR_REGISTRATION_TOKEN_1',
# ...
'YOUR_REGISTRATION_TOKEN_n',
]
# Unubscribe the devices corresponding to the registration tokens from the
# topic.
response = messaging.unsubscribe_from_topic(registration_tokens, topic)
# See the TopicManagementResponse reference documentation
# for the contents of response.
print(response.success_count, 'tokens were unsubscribed successfully')
去
// These registration tokens come from the client FCM SDKs.
registrationTokens := []string{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
}
// Unsubscribe the devices corresponding to the registration tokens from
// the topic.
response, err := client.UnsubscribeFromTopic(ctx, registrationTokens, topic)
if err != nil {
log.Fatalln(err)
}
// See the TopicManagementResponse reference documentation
// for the contents of response.
fmt.Println(response.SuccessCount, "tokens were unsubscribed successfully")
C#
// These registration tokens come from the client FCM SDKs.
var registrationTokens = new List<string>()
{
"YOUR_REGISTRATION_TOKEN_1",
// ...
"YOUR_REGISTRATION_TOKEN_n",
};
// Unsubscribe the devices corresponding to the registration tokens from the
// topic
var response = await FirebaseMessaging.DefaultInstance.UnsubscribeFromTopicAsync(
registrationTokens, topic);
// See the TopicManagementResponse reference documentation
// for the contents of response.
Console.WriteLine($"{response.SuccessCount} tokens were unsubscribed successfully");
subscribeToTopic()
和unsubscribeFromTopic()
方法會產生一個包含來自 FCM 的回應的物件。無論請求中指定的註冊令牌數量如何,返回類型都具有相同的格式。
如果出現錯誤(身份驗證失敗、無效令牌或主題等),這些方法會導致錯誤。有關錯誤代碼的完整清單(包括說明和解決步驟),請參閱管理 FCM API 錯誤。
接收並處理主題訊息
FCM 傳遞主題訊息的方式與其他下游訊息相同。
若要接收訊息,請使用擴充FirebaseMessagingService
服務。您的服務應該覆蓋onMessageReceived
和onDeletedMessages
回呼。
處理訊息的時間視窗可能會短於 20 秒,具體取決於在呼叫onMessageReceived
之前發生的延遲,包括作業系統延遲、應用程式啟動時間、主執行緒被其他操作阻塞或之前的onMessageReceived
呼叫花費太長時間。此後,各種作業系統行為(例如 Android 的進程終止或 Android O 的後台執行限制)可能會幹擾您完成工作的能力。
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}") // Check if data needs to be processed by long running job if (needsToBeScheduled()) { // 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) 或該裝置超過 1 個月沒有連接到 FCM 時,就會發生這種情況。在這些情況下,您可能會收到FirebaseMessagingService.onDeletedMessages()
回呼。當應用程式實例收到此回呼時,它應該與您的應用程式伺服器執行完全同步。如果您在過去 4 週內未向該裝置上的應用程式發送訊息,FCM 將不會呼叫onDeletedMessages()
。處理後台應用程式中的通知訊息
當您的應用程式在背景運行時,Android 會將通知訊息導向到系統托盤。預設情況下,使用者點擊通知會開啟應用程式啟動器。
這包括包含通知和資料負載的訊息(以及從通知控制台發送的所有訊息)。在這些情況下,通知將傳遞到裝置的系統托盤,並且資料負載將在啟動器活動的意圖的附加內容中傳遞。
若要深入了解向您的應用程式發送的訊息,請參閱FCM 報告儀表板,該儀表板記錄Apple 和Android 裝置上發送和開啟的訊息數,以及Android 應用程式的「印象數」(使用者看到的通知)數據。
建構發送請求
建立主題後,您可以透過在客戶端訂閱該主題的客戶端應用程式實例或透過伺服器 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);
Python
# 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)
C#
// 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 -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
若要將訊息傳送到主題組合,請指定條件,它是指定目標主題的布林表達式。例如,以下條件將向訂閱TopicA
以及TopicB
或TopicC
的裝置發送訊息:
"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
FCM 首先計算括號中的任何條件,然後從左到右計算表達式。在上面的表達式中,訂閱任何單一主題的用戶都不會收到訊息。同樣,未訂閱TopicA
用戶也不會收到該訊息。這些組合確實收到了它:
-
TopicA
和TopicB
-
TopicA
和TopicC
您最多可以在條件表達式中包含五個主題。
發送到條件:
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);
Python
# 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)
C#
// 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 -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
下一步
- 了解有關發送到多個設備的其他方式的更多資訊 -設備群組訊息傳遞