Catch up on highlights from Firebase at Google I/O 2023. Learn more

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

Firebase Cloud Messaging มีสองวิธีในการกำหนดเป้าหมายข้อความไปยังอุปกรณ์หลายเครื่อง:

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

ตั้งค่า SDK

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

ก่อนที่คุณจะเริ่มต้น

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

  • ตรวจสอบให้แน่ใจว่าโครงการของคุณตรงตามข้อกำหนดเหล่านี้:

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

  • ลงชื่อเข้าใช้ Firebase โดยใช้บัญชี Google ของคุณ

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

สร้างโครงการ Firebase

ก่อนที่คุณจะเพิ่ม Firebase ลงในแอป Android ได้ คุณต้องสร้างโครงการ Firebase เพื่อเชื่อมต่อกับแอป 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 ) ให้เพิ่มปลั๊กอินบริการของ Google เป็นการพึ่งพา buildscript:

      buildscript {
      
          repositories {
            // Make sure that you have the following two repositories
            google()  // Google's Maven repository
            mavenCentral()  // Maven Central repository
          }
      
          dependencies {
            ...
      
            // Add the dependency for the Google services Gradle plugin
            classpath 'com.google.gms:google-services:4.3.15'
          }
      }
      
      allprojects {
        ...
      
        repositories {
          // Make sure that you have the following two repositories
          google()  // Google's Maven repository
          mavenCentral()  // Maven Central repository
        }
      }
      
    2. ในไฟล์ Gradle ของ โมดูล (ระดับแอป) (โดยปกติคือ <project>/<app-module>/build.gradle ) ให้เพิ่มปลั๊กอินบริการของ Google:

      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 ) ให้เพิ่มการพึ่งพาสำหรับไลบรารี Android ของ Firebase Cloud Messaging ขอแนะนำให้ใช้ Firebase Android BoM เพื่อควบคุมการกำหนดเวอร์ชันของไลบรารี

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

    Java

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.0')
    
        // 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 เวอร์ชันที่เข้ากันได้เสมอ

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

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

    โปรดทราบว่าหากคุณใช้ไลบรารี 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:23.1.2'
        implementation 'com.google.firebase:firebase-analytics:21.3.0'
    }
    

    Kotlin+KTX

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:32.1.0')
    
        // 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-ktx'
        implementation 'com.google.firebase:firebase-analytics-ktx'
    }
    

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

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

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

    โปรดทราบว่าหากคุณใช้ไลบรารี 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-ktx:23.1.2'
        implementation 'com.google.firebase:firebase-analytics-ktx:21.3.0'
    }
    

  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 ควรจัดการข้อความใด ๆ ภายใน 20 วินาทีหลังจากได้รับ (10 วินาทีสำหรับ Android Marshmallow) กรอบเวลาอาจสั้นลงขึ้นอยู่กับความล่าช้าของระบบปฏิบัติการที่เกิดขึ้นก่อนการโทร onMessageReceived หลังจากเวลาดังกล่าว ลักษณะการทำงานต่างๆ ของระบบปฏิบัติการ เช่น ขีดจำกัดการดำเนินการในเบื้องหลัง ของ Android O อาจขัดขวางความสามารถของคุณในการทำงานให้เสร็จ สำหรับข้อมูลเพิ่มเติม โปรดดูภาพรวมของเราเกี่ยวกับ ลำดับความสำคัญของข้อความ

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

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

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

สรุป:

สถานะแอป การแจ้งเตือน ข้อมูล ทั้งคู่
เบื้องหน้า 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 คุณสามารถดำเนินการตามวัตถุ 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 -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 -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

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