Anda dapat membuat aplikasi klien berlangganan topik dari server atau klien:
Di server, menggunakan Firebase Admin SDK.
Di klien, menggunakan API sisi klien dalam aplikasi Anda.
Mengelola langganan topik menggunakan Admin SDK
Firebase Admin SDK dapat Anda gunakan untuk menjalankan tugas dasar pengelolaan topik dari sisi server. Dengan token pendaftaran instance, Anda dapat membuat instance aplikasi klien berlangganan dan berhenti berlangganan secara massal menggunakan logika server.
Anda dapat membuat instance aplikasi klien berlangganan topik yang ada, atau Anda dapat membuat topik baru. Jika Anda menggunakan API untuk membuat aplikasi klien berlangganan topik baru (topik yang belum ada untuk project Firebase Anda), topik baru dengan nama tersebut akan dibuat di FCM sehingga semua klien dapat berlangganan topik tersebut.
Anda dapat meneruskan daftar token pendaftaran ini ke metode langganan Firebase Admin SDK agar perangkat terkait ikut berlangganan topik:
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");
Dengan Firebase Admin SDK, Anda juga dapat menghentikan langganan perangkat dari sebuah topik dengan meneruskan token pendaftaran ke metode yang sesuai:
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");
Metode subscribeToTopic()
dan unsubscribeFromTopic()
menghasilkan objek yang berisi respons dari FCM. Jenis nilai yang ditampilkan memiliki format yang sama berapa pun jumlah token pendaftaran yang ditentukan dalam permintaan.
Jika terjadi error (kegagalan autentikasi, token atau topik tidak valid, dll.), metode ini akan mengakibatkan error. Untuk mengetahui daftar lengkap kode error, termasuk deskripsi dan langkah-langkah penyelesaiannya, lihat bagian Error Firebase Admin SDK.
Mengelola langganan topik dari aplikasi klien Anda
Instance aplikasi klien juga dapat berlangganan atau berhenti berlangganan topik langsung dari aplikasi Anda melalui Firebase SDK. Perhatikan bahwa FCM akan mencoba lagi jika terjadi kegagalan awal untuk memastikan langganan berhasil.
Pilih platform Anda:
Android
Aplikasi klien dapat berlangganan topik yang ada atau membuat topik baru. Jika aplikasi klien berlangganan nama topik baru (nama yang belum ada untuk project Firebase Anda), topik baru dengan nama tersebut akan dibuat di FCM sehingga semua klien dapat berlangganan topik tersebut.
Untuk berlangganan topik, aplikasi klien akan memanggil Firebase Cloud Messaging
subscribeToTopic()
dengan nama topik FCM. Metode ini menampilkan Task
, yang dapat digunakan oleh pemroses penyelesaian untuk menentukan apakah langganan berhasil atau tidak:
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(); } });
Untuk berhenti berlangganan, aplikasi klien akan memanggil Firebase Cloud Messaging unsubscribeFromTopic()
dengan nama topik.
iOS
Aplikasi klien dapat berlangganan topik yang ada atau membuat topik baru. Jika aplikasi klien berlangganan nama topik baru (nama yang belum ada untuk project Firebase Anda), topik baru dengan nama tersebut akan dibuat di FCM sehingga semua klien dapat berlangganan topik tersebut.
Untuk berlangganan topik, panggil metode langganan dari thread utama aplikasi Anda (FCM tidak aman untuk thread). Jika awalnya permintaan langganan gagal, FCM akan mencoba kembali secara otomatis. Jika tidak berhasil diselesaikan, langganan akan menampilkan error yang dapat Anda terima di pengendali penyelesaian seperti yang ditunjukkan berikut:
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"); }];
Panggilan ini mengirimkan permintaan asinkron ke backend FCM dan membuat klien berlangganan topik yang ditentukan. Sebelum memanggil subscribeToTopic:topic
, pastikan bahwa
instance aplikasi klien telah menerima token pendaftaran melalui callback
didReceiveRegistrationToken
.
Setiap kali aplikasi dimulai, FCM akan memastikan bahwa klien telah berlangganan semua topik yang diminta. Untuk menghentikan langganan, panggil
unsubscribeFromTopic:topic
,
dan FCM akan menghentikan langganan topik di latar belakang.
C++
Untuk berlangganan topik, panggil ::firebase::messaging::Subscribe
dari aplikasi Anda. Panggilan ini mengirimkan permintaan asinkron ke backend FCM dan membuat klien berlangganan topik yang ditentukan.
::firebase::messaging::Subscribe("example");
Jika awalnya permintaan langganan gagal, FCM akan mencoba kembali hingga klien berhasil berlangganan topik tersebut. Setiap kali aplikasi dimulai, FCM akan memastikan bahwa klien telah berlangganan semua topik yang diminta.
Untuk menghentikan langganan, panggil ::firebase::messaging::Unsubscribe
, dan FCM akan menghentikan langganan topik di latar belakang.
Unity
Untuk berlangganan topik, panggil Firebase.Messaging.FirebaseMessaging.Subscribe
dari aplikasi Anda. Panggilan ini mengirimkan permintaan asinkron ke backend FCM dan membuat klien berlangganan topik yang ditentukan.
Firebase.Messaging.FirebaseMessaging.Subscribe("/topics/example");
Jika awalnya permintaan langganan gagal, FCM akan mencoba kembali hingga klien berhasil berlangganan topik tersebut. Setiap kali aplikasi dimulai, FCM akan memastikan bahwa klien telah berlangganan semua topik yang diminta.
Untuk menghentikan langganan, panggil
Firebase.Messaging.FirebaseMessaging.Unsubscribe
,
dan FCM akan menghentikan langganan topik di latar belakang.
Pengelolaan Topik Sisi Server Lama (Tidak Digunakan Lagi)
Untuk memahami apa yang dimaksud dengan ID Instance, buka halaman ID Instance. Untuk mengetahui detail tentang endpoint yang tidak digunakan lagi, lihat Referensi API ID Instance.