您可以从服务器或客户端为客户端应用订阅主题:
在服务器上,使用 Firebase Admin SDK。
在客户端上,在应用中使用客户端 API。
使用 Admin SDK 管理主题订阅
借助 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);
});
Java
// 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')
Go
// 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");
利用 Firebase Admin SDK,您还可以将注册令牌传递给相应的方法,来为设备退订主题:
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);
});
Java
// 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')
Go
// 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 响应的对象。无论请求中指定的注册令牌的数量是多少,返回类型的格式都是相同的。
如果出现错误(身份验证失败、令牌或主题无效等),这些方法也会返回错误。如需查看错误代码的完整列表(包括说明和解决方案步骤),请参阅 Firebase Admin SDK 错误。
从客户端应用管理主题订阅
客户端应用实例还可以通过 Firebase SDK 直接从您的应用订阅或退订主题。请注意,如果初始订阅失败,FCM 会进行重试,以确保订阅成功。
选择您的平台:
Android
客户端应用可以订阅任何现有主题,也可以创建新主题。当客户端应用订阅新的主题名称(您的 Firebase 项目中尚不存在的主题)时,系统会在 FCM 中创建一个以该名称命名的新主题,此后任何客户端都可订阅该主题。
如需订阅某个主题,客户端应用需使用 FCM 主题名称调用 Firebase Cloud Messaging subscribeToTopic()
。此方法会返回一个 Task
,完成监听器可以使用它来确定订阅是否成功:
Kotlin
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()
方法。
iOS
客户端应用可以订阅任何现有主题,也可以创建新主题。当客户端应用订阅新的主题名称(您的 Firebase 项目中尚不存在的主题)时,系统会在 FCM 中创建一个以该名称命名的新主题,此后任何客户端都可订阅该主题。
如需订阅一个主题,请从应用的主线程中调用订阅方法(FCM 并不保证线程安全性)。如果初始订阅请求失败,FCM 会自动重试。对于无法完成订阅的情况,订阅会抛出一个错误,您可以在完成处理程序中捕获该错误,如下所示:
Swift
Messaging.messaging().subscribe(toTopic: "weather") { error in print("Subscribed to weather topic") }
Objective-C
[[FIRMessaging messaging] subscribeToTopic:@"weather" completion:^(NSError * _Nullable error) { NSLog(@"Subscribed to weather topic"); }];
此调用会向 FCM 后端发出一个异步请求,并为该客户端订阅指定主题。在调用 subscribeToTopic:topic
之前,请确保客户端应用实例已通过回调函数 didReceiveRegistrationToken
收到注册令牌。
每次应用启动时,FCM 会确保请求的所有主题都已订阅。如需退订主题,请调用 unsubscribeFromTopic:topic
,FCM 即会在后台中退订相关主题。
C++
如需订阅主题,请从应用调用 ::firebase::messaging::Subscribe
。这会向 FCM 后端发出一个异步请求,并为该客户端订阅指定主题。
::firebase::messaging::Subscribe("example");
如果一开始订阅请求失败,FCM 会重试,直至成功订阅该主题。每次应用启动时,FCM 会确保请求的所有主题都已订阅。
如需退订主题,请调用 ::firebase::messaging::Unsubscribe
,FCM 即会在后台中退订相关主题。
Unity
如需订阅主题,请从应用调用 Firebase.Messaging.FirebaseMessaging.Subscribe
。这会向 FCM 后端发出一个异步请求,并为该客户端订阅指定主题。
Firebase.Messaging.FirebaseMessaging.Subscribe("/topics/example");
如果一开始订阅请求失败,FCM 会重试,直至成功订阅该主题。每次应用启动时,FCM 会确保请求的所有主题都已订阅。
如需退订主题,请调用 Firebase.Messaging.FirebaseMessaging.Unsubscribe
,FCM 即会在后台中退订相关主题。
旧版服务器端主题管理(已弃用)
如需了解什么是实例 ID,请访问实例 ID 页面。如需详细了解已弃用的端点,请参阅 Instance ID API 参考文档。