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

หากต้องการกำหนดเป้าหมายข้อความไปยังอุปกรณ์หลายเครื่อง ให้ใช้การรับส่งข้อความตามหัวข้อ ฟีเจอร์นี้ช่วยให้คุณ ส่งข้อความไปยังอุปกรณ์หลายเครื่องที่เลือกรับหัวข้อใดหัวข้อหนึ่งได้

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

ตั้งค่า SDK

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

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

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

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

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

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

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

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

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

  1. ในFirebase คอนโซล ให้คลิกเพิ่มโปรเจ็กต์

    • หากต้องการเพิ่มทรัพยากร Firebase ลงในโปรเจ็กต์ที่มีอยู่ Google Cloud ให้ป้อนชื่อโปรเจ็กต์หรือเลือกจากเมนูแบบเลื่อนลง

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

  2. หากได้รับแจ้ง ให้อ่านและยอมรับข้อกำหนดของ Firebase

  3. คลิกต่อไป

  4. (ไม่บังคับ) ตั้งค่า Google Analytics สำหรับโปรเจ็กต์ ซึ่งจะ ช่วยให้ได้รับประสบการณ์การใช้งานที่ดียิ่งขึ้นเมื่อใช้ผลิตภัณฑ์ Firebase ต่อไปนี้ Firebase A/B Testing Cloud Messaging Crashlytics In-App Messaging และ Remote Config (รวมถึงการปรับเปลี่ยนในแบบของคุณ)

    เลือกบัญชี Google Analytics ที่มีอยู่ หรือสร้างบัญชีใหม่ หากสร้างบัญชีใหม่ ให้เลือกAnalyticsสถานที่ตั้งการรายงาน จากนั้นยอมรับการตั้งค่าการแชร์ข้อมูลและGoogle Analyticsข้อกำหนดสำหรับ โปรเจ็กต์

  5. คลิกสร้างโปรเจ็กต์ (หรือเพิ่ม Firebase หากคุณเพิ่ม Firebase ไปยังโปรเจ็กต์ Google Cloud ที่มีอยู่)

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

ลงทะเบียนแอปกับ Firebase

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

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

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

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

    • ชื่อแพ็กเกจ จะระบุแอปของคุณในอุปกรณ์และ Google Play Store ได้อย่างไม่ซ้ำกัน

    • โดยทั่วไปแล้ว ชื่อแพ็กเกจมักจะเรียกว่ารหัสแอปพลิเคชัน

    • ค้นหาชื่อแพ็กเกจของแอปในไฟล์ Gradle ของโมดูล (ระดับแอป) ซึ่งโดยปกติคือ app/build.gradle (ตัวอย่างชื่อแพ็กเกจ: com.yourcompany.yourproject)

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

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

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

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

  1. ดาวน์โหลดแล้วเพิ่มไฟล์กำหนดค่า Firebase ของแอป (google-services.json) ลงในโค้ดเบส

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

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

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

    • คุณดาวน์โหลดไฟล์กำหนดค่า Firebase อีกครั้งได้ทุกเมื่อ

    • โปรดตรวจสอบว่าชื่อไฟล์การกำหนดค่าไม่มีอักขระต่อท้ายเพิ่มเติม เช่น (2)

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

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

      KotlinGroovy
      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.3" apply false
      }
      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.3' apply false
      }
    2. ในไฟล์ Gradle ของโมดูล (ระดับแอป) (โดยปกติคือ <project>/<app-module>/build.gradle.kts หรือ <project>/<app-module>/build.gradle) ให้เพิ่มปลั๊กอินบริการของ Google ดังนี้

      KotlinGroovy
      plugins {
        id("com.android.application")
      
        // Add the Google services Gradle plugin
        id("com.google.gms.google-services")
        // ...
      }
      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 เราขอแนะนำให้ใช้ Firebase Android BoM เพื่อควบคุมการควบคุมเวอร์ชันของไลบรารี

    เพื่อประสบการณ์การใช้งาน 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:34.0.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 แต่ละรายการ ในบรรทัดการอ้างอิง

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

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

    บิลด์ Gradle ที่ใช้ปลั๊กอิน Android Gradle (AGP) เวอร์ชัน 4.2 หรือก่อนหน้าต้อง เปิดใช้การรองรับ Java 8 ไม่เช่นนั้น โปรเจ็กต์ Android เหล่านี้จะสร้างไม่สำเร็จเมื่อเพิ่ม Firebase SDK

    หากต้องการแก้ไขการสร้างที่ไม่สำเร็จนี้ คุณสามารถทำตามตัวเลือกใดตัวเลือกหนึ่งต่อไปนี้

    • เพิ่ม compileOptions ที่ระบุไว้ในข้อความแสดงข้อผิดพลาดลงในไฟล์ build.gradle.kts หรือ build.gradle ระดับแอป
    • เพิ่ม minSdk สำหรับโปรเจ็กต์ Android เป็น 26 ขึ้นไป

    ดูข้อมูลเพิ่มเติมเกี่ยวกับการล้มเหลวของบิลด์นี้ได้ในคำถามที่พบบ่อยนี้

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

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

หากต้องการสมัครรับข้อมูลหัวข้อ แอปไคลเอ็นต์จะเรียกใช้ Firebase Cloud Messaging subscribeToTopic() โดยมีชื่อหัวข้อ FCM เมธอดนี้ จะแสดงผล Task ซึ่ง Listener การเสร็จสมบูรณ์ใช้เพื่อพิจารณาว่า การสมัครใช้บริการสำเร็จหรือไม่

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

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

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

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

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

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

แก้ไขไฟล์ 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 ที่ได้รับและรับข้อมูลข้อความได้

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

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

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

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

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

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

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

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

Node.jsJavaPythonGoC#REST
// 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

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

หากต้องการส่งไปยังเงื่อนไข ให้ทำดังนี้

Node.jsJavaPythonGoC#REST
// 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

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