การส่งข้อความหัวข้อบน Android

ตามรูปแบบการเผยแพร่/สมัครสมาชิก ข้อความหัวข้อ FCM ช่วยให้คุณสามารถส่งข้อความไปยังอุปกรณ์หลายเครื่องที่เลือกใช้หัวข้อใดหัวข้อหนึ่งได้ คุณเขียนข้อความหัวข้อตามต้องการ และ FCM จะจัดการการกำหนดเส้นทางและส่งข้อความไปยังอุปกรณ์ที่เหมาะสมได้อย่างน่าเชื่อถือ

ตัวอย่างเช่น ผู้ใช้แอปคาดการณ์น้ำขึ้นน้ำลงในท้องถิ่นสามารถเลือกเข้าร่วมหัวข้อ "การแจ้งเตือนกระแสน้ำขึ้นน้ำลง" และรับการแจ้งเตือนเกี่ยวกับสภาวะการจับปลาน้ำเค็มที่เหมาะสมที่สุดในพื้นที่ที่ระบุ ผู้ใช้แอปกีฬาสามารถสมัครรับการอัปเดตอัตโนมัติในคะแนนการแข่งขันสดของทีมโปรดของตนได้

สิ่งที่ควรคำนึงถึงเกี่ยวกับหัวข้อต่างๆ:

  • ข้อความหัวข้อเหมาะที่สุดสำหรับเนื้อหา เช่น สภาพอากาศ หรือข้อมูลที่เปิดเผยต่อสาธารณะอื่นๆ
  • ข้อความหัวข้อได้ รับการปรับให้เหมาะสมสำหรับปริมาณงานมากกว่าเวลาในการตอบสนอง เพื่อการจัดส่งที่รวดเร็วและปลอดภัยไปยังอุปกรณ์เดี่ยวหรืออุปกรณ์กลุ่มเล็กๆ ให้กำหนดเป้าหมายข้อความไปที่โทเค็นการลงทะเบียน ไม่ใช่หัวข้อ
  • หากคุณต้องการส่งข้อความไปยังอุปกรณ์หลายเครื่อง ต่อผู้ใช้ ลองใช้การรับ ส่งข้อความกลุ่มอุปกรณ์ สำหรับกรณีการใช้งานเหล่านั้น
  • การส่งข้อความหัวข้อรองรับการสมัครสมาชิกไม่จำกัดสำหรับแต่ละหัวข้อ อย่างไรก็ตาม FCM บังคับใช้ข้อจำกัดในด้านเหล่านี้:
    • หนึ่งอินสแตนซ์ของแอปสามารถสมัครรับหัวข้อได้ไม่เกิน 2,000 หัวข้อ
    • หากคุณใช้ การนำเข้าเป็นกลุ่ม เพื่อสมัครใช้งานอินสแตนซ์ของแอป แต่ละคำขอจะถูกจำกัดไว้ที่ 1,000 อินสแตนซ์ของแอป
    • ความถี่ของการสมัครสมาชิกใหม่มีการจำกัดอัตราต่อโปรเจ็กต์ หากคุณส่งคำขอสมัครสมาชิกมากเกินไปในช่วงเวลาสั้นๆ เซิร์ฟเวอร์ FCM จะตอบกลับด้วยการตอบสนอง 429 RESOURCE_EXHAUSTED ("เกินโควต้า") ลองอีกครั้งโดยใช้การถอยกลับแบบเอ็กซ์โปเนนเชียล

สมัครสมาชิกแอปไคลเอนต์ในหัวข้อ

แอปไคลเอนต์สามารถสมัครรับหัวข้อที่มีอยู่หรือสามารถสร้างหัวข้อใหม่ได้ เมื่อแอปไคลเอนต์สมัครรับชื่อหัวข้อใหม่ (ที่ไม่มีอยู่แล้วสำหรับโปรเจ็กต์ Firebase ของคุณ) หัวข้อใหม่ของชื่อนั้นจะถูกสร้างขึ้นใน FCM และไคลเอนต์ใด ๆ ก็สามารถสมัครรับชื่อนั้นได้ในภายหลัง

หากต้องการสมัครรับหัวข้อ แอปไคลเอนต์จะเรียก Firebase Cloud Messaging subscribeToTopic() พร้อมชื่อหัวข้อ FCM เมธอดนี้ส่งคืน 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 เพื่อสมัครสมาชิกอุปกรณ์ที่เกี่ยวข้องในหัวข้อ:

โหนด 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");

หลาม

# 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 ยังช่วยให้คุณยกเลิกการสมัครอุปกรณ์จากหัวข้อโดยส่งโทเค็นการลงทะเบียนไปยังวิธีการที่เหมาะสม:

โหนด 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");

หลาม

# 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 วินาที ขึ้นอยู่กับความล่าช้าที่เกิดขึ้นก่อนการเรียก 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) ที่รอดำเนินการสำหรับแอปของคุณบนอุปกรณ์ใดอุปกรณ์หนึ่งในขณะที่เชื่อมต่อ หรือหากอุปกรณ์ไม่ได้เชื่อมต่อกับ FCM เป็นเวลานานกว่าหนึ่งเดือน ในกรณีเหล่านี้ คุณอาจได้รับการเรียกกลับไปยัง FirebaseMessagingService.onDeletedMessages() เมื่ออินสแตนซ์ของแอปได้รับการเรียกกลับนี้ อินสแตนซ์ควรทำการซิงค์แบบเต็มกับเซิร์ฟเวอร์แอปของคุณ หากคุณไม่ได้ส่งข้อความไปยังแอปบนอุปกรณ์นั้นภายใน 4 สัปดาห์ที่ผ่านมา FCM จะไม่เรียก onDeletedMessages()

จัดการข้อความแจ้งเตือนในแอปที่ทำงานอยู่เบื้องหลัง

เมื่อแอปของคุณอยู่ในพื้นหลัง Android จะส่งข้อความแจ้งเตือนไปยังถาดระบบ ผู้ใช้แตะที่การแจ้งเตือนจะเปิดตัวเปิดแอปตามค่าเริ่มต้น

ซึ่งรวมถึงข้อความที่มีทั้งการแจ้งเตือนและเพย์โหลดข้อมูล (และข้อความทั้งหมดที่ส่งจากคอนโซลการแจ้งเตือน) ในกรณีเหล่านี้ การแจ้งเตือนจะถูกส่งไปยังถาดระบบของอุปกรณ์ และเพย์โหลดข้อมูลจะถูกส่งไปในส่วนเพิ่มเติมจากจุดประสงค์ของกิจกรรมตัวเรียกใช้งานของคุณ

หากต้องการข้อมูลเชิงลึกเกี่ยวกับการส่งข้อความไปยังแอปของคุณ โปรดดูแด ชบอร์ดการรายงาน FCM ซึ่งจะบันทึกจำนวนข้อความที่ส่งและเปิดบนอุปกรณ์ Apple และ Android พร้อมด้วยข้อมูลสำหรับ "การแสดงผล" (การแจ้งเตือนที่ผู้ใช้เห็น) สำหรับแอป Android

สร้างคำขอส่ง

หลังจากที่คุณสร้างหัวข้อแล้ว โดยการสมัครอินสแตนซ์แอปไคลเอ็นต์กับหัวข้อในฝั่งไคลเอ็นต์หรือผ่าน API ของเซิร์ฟเวอร์ คุณสามารถส่งข้อความไปยังหัวข้อได้ หากนี่เป็นครั้งแรกที่คุณสร้างส่งคำขอสำหรับ FCM โปรดดูคำแนะนำเกี่ยวกับ สภาพแวดล้อมเซิร์ฟเวอร์ของคุณและ FCM สำหรับข้อมูลพื้นหลังและการตั้งค่าที่สำคัญ

ในตรรกะการส่งของคุณบนแบ็กเอนด์ ให้ระบุชื่อหัวข้อที่ต้องการตามที่แสดง:

โหนด 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

หากต้องการส่งข้อความไปยังหัวข้อต่างๆ รวมกัน ให้ระบุ เงื่อนไข ซึ่งเป็นนิพจน์บูลีนที่ระบุหัวข้อเป้าหมาย ตัวอย่างเช่น เงื่อนไขต่อไปนี้จะส่งข้อความไปยังอุปกรณ์ที่สมัครรับ TopicA และ TopicB หรือ TopicC :

"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"

FCM จะประเมินเงื่อนไขใดๆ ในวงเล็บก่อน จากนั้นจึงประเมินนิพจน์จากซ้ายไปขวา ในนิพจน์ข้างต้น ผู้ใช้ที่สมัครรับข้อมูลหัวข้อใดหัวข้อหนึ่งจะไม่ได้รับข้อความ ในทำนองเดียวกัน ผู้ใช้ที่ไม่ได้สมัครสมาชิก TopicA จะไม่ได้รับข้อความ ชุดค่าผสมเหล่านี้ได้รับ:

  • TopicA และ TopicB
  • TopicA และ TopicC

คุณสามารถรวมหัวข้อได้สูงสุดห้าหัวข้อในนิพจน์แบบมีเงื่อนไขของคุณ

หากต้องการส่งตามเงื่อนไข:

โหนด 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

ขั้นตอนถัดไป