ส่งข้อความไปยังอุปกรณ์หลายเครื่อง

ในการกำหนดเป้าหมายข้อความไปยังอุปกรณ์หลายเครื่อง ให้ใช้ ข้อความตามหัวข้อ ช่วงเวลานี้ ที่ช่วยให้คุณดำเนินการ ส่งข้อความไปยังอุปกรณ์หลายเครื่องที่เลือกเข้าร่วมหัวข้อเฉพาะได้

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

ตั้งค่า SDK

ส่วนนี้อาจครอบคลุมขั้นตอนที่คุณได้ดำเนินการไปแล้ว หากคุณ ตั้งค่าแอปไคลเอ็นต์ Android แล้ว สำหรับ FCM หรือทำตามขั้นตอน ส่งข้อความแรกของคุณ

ก่อนเริ่มต้น

  • ติดตั้งหรืออัปเดต Android Studio ให้เป็นเวอร์ชันล่าสุด

  • ตรวจสอบให้แน่ใจว่าโปรเจ็กต์ของคุณเป็นไปตามข้อกำหนดเหล่านี้ (โปรดทราบว่าผลิตภัณฑ์บางรายการ อาจมีข้อกำหนดที่เข้มงวดกว่า) ดังนี้

    • API เป้าหมายระดับ 19 (KitKat) ขึ้นไป
    • ใช้ Android 4.4 ขึ้นไป
    • การใช้งาน Jetpack (AndroidX) ซึ่งมีคุณสมบัติตรงตามข้อกำหนดของเวอร์ชันเหล่านี้
      • com.android.tools.build:gradle v7.3.0 ขึ้นไป
      • compileSdkVersion 28 ขึ้นไป
  • ตั้งค่าอุปกรณ์จริงหรือใช้อุปกรณ์ โปรแกรมจำลองเพื่อ เรียกใช้แอปของคุณ
    โปรดทราบว่า Firebase SDK ที่ใช้ทรัพยากร Dependency ใน Google Play บริการต้องใช้อุปกรณ์หรือ โปรแกรมจำลองเพื่อติดตั้งบริการ Google Play

  • ลงชื่อเข้าใช้ Firebase โดยใช้ ของคุณได้

หากยังไม่มีโปรเจ็กต์ Android และต้องการลองใช้ Firebase คุณสามารถดาวน์โหลดตัวอย่างการเริ่มต้นอย่างรวดเร็วของเราได้

สร้างโปรเจ็กต์ Firebase

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

ลงทะเบียนแอปด้วย Firebase

หากต้องการใช้ Firebase ในแอป Android คุณต้องลงทะเบียนแอปด้วย โปรเจ็กต์ Firebase การลงทะเบียนแอปมักเรียกว่า "การเพิ่ม" แอปของคุณไปยัง

  1. ไปที่คอนโซล Firebase

  2. ที่ตรงกลางของหน้าภาพรวมโปรเจ็กต์ ให้คลิกไอคอน Android () หรือเพิ่มแอปเพื่อเปิดเวิร์กโฟลว์การตั้งค่า

  3. ป้อนชื่อแพ็กเกจของแอปในช่องชื่อแพ็กเกจ Android

  4. (ไม่บังคับ) ป้อนข้อมูลอื่นๆ ของแอป ชื่อเล่นแอปและแก้ไขข้อบกพร่องการลงนามใบรับรอง SHA-1

  5. คลิกลงทะเบียนแอป

เพิ่มไฟล์การกำหนดค่า Firebase

  1. ดาวน์โหลดแล้วเพิ่มไฟล์การกำหนดค่า Firebase Android (google-services.json) ไปยังแอปของคุณ:

    1. คลิกดาวน์โหลด google-services.json เพื่อรับ Firebase Android ไฟล์การกำหนดค่าเซิร์ฟเวอร์

    2. ย้ายไฟล์การกำหนดค่าลงในไดเรกทอรีรากโมดูล (ระดับแอป) ของ แอปของคุณ

  2. หากต้องการทำให้ค่าในไฟล์การกำหนดค่า google-services.json เข้าถึงได้ Firebase SDK ปลั๊กอิน Gradle สำหรับบริการของ Google (google-services)

    1. ในไฟล์ Gradle ระดับราก (ระดับโปรเจ็กต์) (<project>/build.gradle.kts หรือ <project>/build.gradle) ให้เพิ่ม ปลั๊กอินบริการของ Google เป็นทรัพยากร Dependency:

      Kotlin

      plugins {
        id("com.android.application") version "7.3.0" apply false
        // ...
      
        // Add the dependency for the Google services Gradle plugin
        id("com.google.gms.google-services") version "4.4.2" apply false
      }
      

      Groovy

      plugins {
        id 'com.android.application' version '7.3.0' apply false
        // ...
      
        // Add the dependency for the Google services Gradle plugin
        id 'com.google.gms.google-services' version '4.4.2' apply false
      }
      
    2. ในไฟล์ Gradle ของโมดูล (ระดับแอป) (ปกติ <project>/<app-module>/build.gradle.kts หรือ <project>/<app-module>/build.gradle) เพิ่มปลั๊กอินบริการของ Google:

      Kotlin

      plugins {
        id("com.android.application")
      
        // Add the Google services Gradle plugin
        id("com.google.gms.google-services")
        // ...
      }
      

      Groovy

      plugins {
        id 'com.android.application'
      
        // Add the Google services Gradle plugin
        id 'com.google.gms.google-services'
        // ...
      }
      

เพิ่ม Firebase SDK ลงในแอป

  1. ในไฟล์ Gradle ของโมดูล (ระดับแอป) (ปกติ <project>/<app-module>/build.gradle.kts หรือ <project>/<app-module>/build.gradle) เพิ่มทรัพยากร Dependency สำหรับไลบรารี Firebase Cloud Messaging สำหรับ Android เราขอแนะนำให้ใช้ BoM ของ Firebase Android เพื่อควบคุมการกำหนดเวอร์ชันไลบรารี

    หากต้องการสัมผัสประสบการณ์การใช้งาน Firebase Cloud Messaging ที่ดีที่สุด เราขอแนะนำ การเปิดใช้ Google Analytics ในโปรเจ็กต์ Firebase และเพิ่ม Firebase SDK สำหรับ Google Analytics ลงในแอป

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:33.1.2"))
    
        // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-messaging")
        implementation("com.google.firebase:firebase-analytics")
    }
    

    การใช้ Firebase Android BoM แอปจะใช้ไลบรารี Firebase Android เวอร์ชันที่เข้ากันได้เสมอ

    (ทางเลือก) เพิ่มทรัพยากร Dependency ของไลบรารี Firebase โดยไม่ต้องใช้ BoM

    หากเลือกไม่ใช้ Firebase BoM คุณต้องระบุเวอร์ชันไลบรารี Firebase แต่ละเวอร์ชัน ในบรรทัดทรัพยากร Dependency

    โปรดทราบว่าหากคุณใช้ไลบรารี Firebase หลายรายการในแอป เราขอแนะนำอย่างยิ่ง ขอแนะนำให้ใช้ BoM ในการจัดการเวอร์ชันไลบรารี เพื่อดูแลให้ทุกเวอร์ชัน ที่เข้ากันได้

    dependencies {
        // Add the dependencies for the Firebase Cloud Messaging and Analytics libraries
        // When NOT using the BoM, you must specify versions in Firebase library dependencies
        implementation("com.google.firebase:firebase-messaging:24.0.0")
        implementation("com.google.firebase:firebase-analytics:22.0.2")
    }
    
    หากกำลังมองหาโมดูลไลบรารีสำหรับ Kotlin โดยเฉพาะ จะเริ่มต้นใน ตุลาคม 2023 (Firebase BoM 32.5.0) ทั้งนักพัฒนาซอฟต์แวร์ Kotlin และ Java สามารถ ขึ้นอยู่กับโมดูลไลบรารีหลัก (ดูรายละเอียดได้ที่ คําถามที่พบบ่อยเกี่ยวกับโครงการริเริ่มนี้)

  2. ซิงค์โปรเจ็กต์ Android กับไฟล์ Gradle

สมัครรับข้อมูลหัวข้อในแอปไคลเอ็นต์

แอปไคลเอ็นต์สามารถสมัครรับข้อมูลหัวข้อที่มีอยู่ หรือสามารถสร้างหัวข้อใหม่ หัวข้อ เมื่อแอปไคลเอ็นต์สมัครรับชื่อหัวข้อใหม่ (ประเภทที่ สำหรับโปรเจ็กต์ 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() ด้วยชื่อหัวข้อ

รับและจัดการข้อความตามหัวข้อ

FCM ส่งข้อความหัวข้อในลักษณะเดียวกับที่ปลายทางอื่นๆ ข้อความ

ในการรับข้อความ โปรดใช้บริการแบบขยาย FirebaseMessagingService บริการของคุณควรลบล้าง onMessageReceived และ onDeletedMessages Callback

กรอบเวลาในการจัดการข้อความอาจสั้นกว่า 20 วินาที ขึ้นอยู่กับความล่าช้าต่างๆ เกิดขึ้นก่อนการเรียกใช้ onMessageReceived ซึ่งรวมถึงความล่าช้าของระบบปฏิบัติการ เวลาเริ่มต้นแอป เทรดหลักถูกบล็อกโดยการดำเนินการอื่นๆ หรือ onMessageReceived ก่อนหน้า การโทรใช้เวลานานเกินไป หลังจากนั้น ลักษณะการทำงานต่างๆ ของระบบปฏิบัติการ เช่น ประมวลผล การหยุดทำงาน หรือของ Android O ขีดจำกัดการดำเนินการในเบื้องหลังอาจรบกวนความสามารถในการทำงานของคุณ

onMessageReceived มีให้สำหรับข้อความส่วนใหญ่ โดยมีสิ่งต่อไปนี้ ข้อยกเว้น:

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

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

บทสรุปมีดังนี้:

สถานะของแอป การแจ้งเตือน ข้อมูล ทั้งสอง
พื้นหน้า onMessageReceived onMessageReceived onMessageReceived
ความเป็นมา ถาดระบบ onMessageReceived การแจ้งเตือน: ถาดระบบ
ข้อมูล: ข้อมูลเพิ่มเติมเกี่ยวกับความตั้งใจ
โปรดดูข้อมูลเพิ่มเติมเกี่ยวกับประเภทข้อความที่หัวข้อ การแจ้งเตือนและ ข้อความข้อมูล

แก้ไขไฟล์ Manifest ของแอป

หากต้องการใช้FirebaseMessagingService คุณต้องเพิ่มสิ่งต่อไปนี้ใน ไฟล์ Manifest ของแอป:

<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 คุณสามารถดำเนินการตาม ข้อความระยะไกล และรับข้อมูลข้อความ:

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

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

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

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

ดูข้อมูลเชิงลึกเกี่ยวกับการส่งข้อความไปที่แอปได้ที่ แดชบอร์ดการรายงาน 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);
  });

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)

Go

// 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);

REST

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

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

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

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

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

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

วิธีส่งไปยังเงื่อนไข

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)

Go

// 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);

REST

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

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