ตามรูปแบบการเผยแพร่/สมัครรับข่าวสาร การส่งข้อความตามหัวข้อ FCM ช่วยให้คุณสามารถส่งข้อความไปยังอุปกรณ์หลายเครื่องที่เลือกใช้หัวข้อเฉพาะ คุณเขียนข้อความหัวข้อตามความจำเป็น และ FCM จะจัดการการกำหนดเส้นทางและส่งข้อความไปยังอุปกรณ์ที่เหมาะสมได้อย่างน่าเชื่อถือ
ตัวอย่างเช่น ผู้ใช้แอปพยากรณ์น้ำในพื้นที่สามารถเลือกหัวข้อ "การแจ้งเตือนกระแสน้ำขึ้นน้ำลง" และรับการแจ้งเตือนเกี่ยวกับสภาพการตกปลาน้ำเค็มที่เหมาะสมที่สุดในพื้นที่ที่กำหนด ผู้ใช้แอปกีฬาสามารถสมัครรับการอัปเดตอัตโนมัติในคะแนนเกมสดสำหรับทีมโปรดของพวกเขา
สิ่งที่ควรทราบเกี่ยวกับหัวข้อ:
- ข้อความหัวข้อเหมาะที่สุดสำหรับเนื้อหา เช่น สภาพอากาศ หรือข้อมูลอื่นๆ ที่เปิดเผยต่อสาธารณะ
- ข้อความหัวข้อได้รับ การปรับให้เหมาะสมสำหรับปริมาณงานมากกว่าเวลาในการตอบสนอง เพื่อการส่งที่รวดเร็วและปลอดภัยไปยังอุปกรณ์เครื่องเดียวหรือกลุ่มอุปกรณ์ขนาดเล็ก ให้ กำหนดเป้าหมายข้อความไปยังโทเค็นการลงทะเบียน ไม่ใช่หัวข้อ
- หากคุณต้องการส่งข้อความไปยังอุปกรณ์หลายเครื่อง ต่อผู้ใช้หนึ่งราย ให้พิจารณา การส่งข้อความกลุ่มอุปกรณ์ สำหรับกรณีการใช้งานเหล่านั้น
- การส่งข้อความตามหัวข้อรองรับการสมัครรับข้อมูลแบบไม่จำกัดสำหรับแต่ละหัวข้อ อย่างไรก็ตาม FCM บังคับใช้ข้อจำกัดในพื้นที่เหล่านี้:
- อินสแตนซ์แอปหนึ่งรายการสามารถสมัครรับข้อมูลได้ไม่เกิน 2,000 หัวข้อ
- หากคุณกำลังใช้ การนำเข้าแบบกลุ่ม เพื่อสมัครใช้งานอินสแตนซ์ของแอป คำขอแต่ละรายการจะถูกจำกัดที่ 1,000 อินสแตนซ์ของแอป
- ความถี่ของการสมัครรับข้อมูลใหม่ถูกจำกัดอัตราต่อโครงการ หากคุณส่งคำขอสมัครรับข้อมูลมากเกินไปในระยะเวลาอันสั้น เซิร์ฟเวอร์ FCM จะตอบสนองด้วยการตอบกลับ
429 RESOURCE_EXHAUSTED
("เกินโควต้า") ลองอีกครั้งด้วยการถอยกลับแบบเอ็กซ์โปเนนเชียล
สมัครสมาชิกแอพไคลเอนต์ในหัวข้อ
แอปไคลเอนต์สามารถสมัครรับหัวข้อที่มีอยู่หรือสร้างหัวข้อใหม่ได้ เมื่อแอปไคลเอ็นต์สมัครรับชื่อหัวข้อใหม่ (ชื่อที่ไม่มีอยู่ในโปรเจ็กต์ Firebase ของคุณ) หัวข้อใหม่ของชื่อนั้นจะถูกสร้างขึ้นใน FCM และไคลเอ็นต์ใดๆ ก็สามารถสมัครรับข้อมูลได้ในภายหลัง
หากต้องการสมัครรับหัวข้อ แอปไคลเอ็นต์จะเรียก Firebase Cloud Messaging subscribeToTopic()
ด้วยชื่อหัวข้อ FCM เมธอดนี้ส่งคืน Task
ซึ่งสามารถใช้โดยผู้ฟังที่สมบูรณ์เพื่อพิจารณาว่าการสมัครรับข้อมูลสำเร็จหรือไม่:
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(); } });
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() }
หากต้องการยกเลิกการสมัคร แอปไคลเอ็นต์จะเรียก 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);
});
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')
ไป
// 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")
ค#
// 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");
Admin 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);
});
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')
ไป
// 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")
ค#
// 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 ประเภทการส่งคืนมีรูปแบบเดียวกันโดยไม่คำนึงถึงจำนวนของโทเค็นการลงทะเบียนที่ระบุในคำขอ
ในกรณีที่เกิดข้อผิดพลาด (การตรวจสอบล้มเหลว โทเค็นหรือหัวข้อไม่ถูกต้อง ฯลฯ) วิธีการเหล่านี้ส่งผลให้เกิดข้อผิดพลาด สำหรับรายการรหัสข้อผิดพลาดทั้งหมด รวมถึงคำอธิบายและขั้นตอนการแก้ปัญหา โปรดดูที่ ข้อผิดพลาด Admin FCM API
รับและจัดการข้อความหัวข้อ
FCM ส่งข้อความหัวข้อในลักษณะเดียวกับข้อความปลายทางอื่นๆ
หากต้องการรับข้อความ ให้ใช้บริการที่ขยาย FirebaseMessagingService บริการของคุณควรแทนที่การเรียกกลับ onMessageReceived
และ onDeletedMessages
ควรจัดการข้อความภายใน 20 วินาทีหลังจากได้รับ (10 วินาทีใน Android Marshmallow) กรอบเวลาอาจสั้นลงขึ้นอยู่กับความล่าช้าของระบบปฏิบัติการที่เกิดขึ้นก่อนการโทรบน onMessageReceived
หลังจากเวลานั้น ลักษณะการทำงานของระบบปฏิบัติการต่างๆ เช่น ขีดจำกัดการดำเนินการในเบื้องหลัง ของ 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 ที่ได้รับและรับข้อมูลข้อความ:
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. }
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. }
แทนที่ onDeletedMessages
ในบางสถานการณ์ FCM อาจไม่ส่งข้อความ กรณีนี้เกิดขึ้นเมื่อมีข้อความที่รอดำเนินการมากเกินไป (>100) สำหรับแอปของคุณบนอุปกรณ์เฉพาะในขณะที่เชื่อมต่อ หรือหากอุปกรณ์ไม่ได้เชื่อมต่อกับ FCM เป็นเวลานานกว่าหนึ่งเดือน ในกรณีเหล่านี้ คุณอาจได้รับการเรียกกลับไปยัง FirebaseMessagingService.onDeletedMessages()
เมื่ออินสแตนซ์ของแอปได้รับการเรียกกลับนี้ อินสแตนซ์ควรทำการซิงค์อย่างสมบูรณ์กับเซิร์ฟเวอร์แอปของคุณ หากคุณไม่ได้ส่งข้อความไปยังแอปบนอุปกรณ์นั้นภายใน 4 สัปดาห์ที่ผ่านมา FCM จะไม่เรียก onDeletedMessages()
จัดการข้อความแจ้งเตือนในแอพพื้นหลัง
เมื่อแอปของคุณอยู่ในพื้นหลัง Android จะส่งข้อความแจ้งเตือนไปยังซิสเต็มเทรย์ ผู้ใช้แตะที่การแจ้งเตือนจะเปิดตัวเรียกใช้งานแอปตามค่าเริ่มต้น
ซึ่งรวมถึงข้อความที่มีทั้งส่วนของการแจ้งเตือนและข้อมูล (และข้อความทั้งหมดที่ส่งจากคอนโซลการแจ้งเตือน) ในกรณีเหล่านี้ การแจ้งเตือนจะถูกส่งไปยังซิสเต็มเทรย์ของอุปกรณ์ และเพย์โหลดข้อมูลจะถูกส่งในส่วนเพิ่มเติมของเจตนาของกิจกรรมตัวเรียกใช้งานของคุณ
สำหรับข้อมูลเชิงลึกเกี่ยวกับการส่งข้อความไปยังแอปของคุณ โปรดดู แดชบอร์ดการรายงาน FCM ซึ่งบันทึกจำนวนข้อความที่ส่งและเปิดบนอุปกรณ์ Apple และ Android พร้อมด้วยข้อมูลสำหรับ "การแสดงผล" (การแจ้งเตือนที่ผู้ใช้เห็น) สำหรับแอป Android
แอปที่จำกัดในเบื้องหลัง (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);
});
Java
// 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)
ค#
// 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
ในการส่งข้อความไปยังหัวข้อต่างๆ รวมกัน ให้ระบุ เงื่อนไข ซึ่งเป็นนิพจน์บูลีนที่ระบุหัวข้อเป้าหมาย ตัวอย่างเช่น เงื่อนไขต่อไปนี้จะส่งข้อความไปยังอุปกรณ์ที่สมัครใช้ 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);
});
Java
// 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)
ค#
// 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
ขั้นตอนถัดไป
- เรียนรู้เพิ่มเติมเกี่ยวกับวิธีอื่นในการส่งไปยังอุปกรณ์หลายเครื่อง — การส่งข้อความกลุ่มอุปกรณ์