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 การลงทะเบียนแอพของคุณมักจะเรียกว่า "การเพิ่ม" แอพของคุณในโครงการของคุณ
ไปที่ คอนโซล Firebase
ตรงกลางหน้าภาพรวมโครงการ ให้คลิกไอคอน Android (
) หรือ เพิ่มแอป เพื่อเริ่มเวิร์กโฟลว์การตั้งค่าป้อนชื่อแพ็กเกจของแอปในช่อง ชื่อแพ็กเกจ Android
ชื่อแพ็กเกจ จะระบุแอปของคุณบนอุปกรณ์และใน Google Play Store โดยไม่ซ้ำกัน
ชื่อแพ็คเกจ มักถูกเรียกว่า ID แอปพลิเคชัน
ค้นหาชื่อแพ็คเกจของแอปในไฟล์ Gradle ของโมดูล (ระดับแอป) ซึ่งมักจะเป็น
app/build.gradle
(ชื่อแพ็คเกจตัวอย่าง:com.yourcompany.yourproject
)โปรดทราบว่าค่าชื่อแพ็กเกจจะคำนึงถึงตัวพิมพ์เล็กและตัวพิมพ์ใหญ่ และไม่สามารถเปลี่ยนแปลงได้สำหรับแอป Firebase Android นี้หลังจากที่ลงทะเบียนกับโปรเจ็กต์ Firebase แล้ว
(ไม่บังคับ) ป้อนข้อมูลแอปอื่นๆ: ชื่อเล่นแอป และ ใบรับรองการลงนามดีบัก SHA-1
ชื่อเล่นของแอป : ตัวระบุความสะดวกภายในที่มีคุณเท่านั้นที่เห็นในคอนโซล Firebase
ดีบักใบรับรองการเซ็นชื่อ SHA-1 : จำเป็นต้องมี แฮช SHA-1 โดย Firebase Authentication (เมื่อใช้ Google Sign In หรือ หมายเลขโทรศัพท์ลงชื่อเข้าใช้ ) และ Firebase Dynamic Links
คลิก ลงทะเบียนแอป
เพิ่มไฟล์การกำหนดค่า Firebase
เพิ่มไฟล์การกำหนดค่า Firebase Android ในแอปของคุณ:
คลิก ดาวน์โหลด google-services.json เพื่อรับไฟล์กำหนดค่า Firebase Android ของคุณ (
)google-services.json ย้ายไฟล์ปรับแต่งของคุณไปที่ไดเร็กทอรีโมดูล (ระดับแอพ) ของแอพของคุณ
ไฟล์กำหนดค่า Firebase มีตัวระบุที่ไม่ซ้ำแต่ไม่เป็นความลับสำหรับโปรเจ็กต์ของคุณ หากต้องการเรียนรู้เพิ่มเติมเกี่ยวกับไฟล์กำหนดค่านี้ โปรดไปที่ ทำความเข้าใจโปรเจ็กต์ Firebase
คุณดาวน์โหลด ไฟล์กำหนดค่า Firebase อีกครั้งได้ทุกเมื่อ
ตรวจสอบให้แน่ใจว่าชื่อไฟล์ปรับแต่งไม่ได้ต่อท้ายด้วยอักขระเพิ่มเติม เช่น
(2)
หากต้องการเปิดใช้งานผลิตภัณฑ์ Firebase ในแอปของคุณ ให้เพิ่ม ปลั๊กอิน google-services ลงในไฟล์ Gradle ของคุณ
ในไฟล์ Gradle ระดับราก (ระดับโปรเจ็กต์) ของคุณ (
build.gradle
) ให้เพิ่มกฎเพื่อรวมปลั๊กอิน Google Services Gradle ตรวจสอบว่าคุณมีที่เก็บ Maven ของ Google ด้วยbuildscript { repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository } dependencies { // ... // Add the following line: classpath 'com.google.gms:google-services:4.3.13' // Google Services plugin } } allprojects { // ... repositories { // Check that you have the following line (if not, add it): google() // Google's Maven repository // ... } }
ในไฟล์ Gradle ของโมดูล (ระดับแอป) (โดยปกติคือ
app/build.gradle
) ใช้ปลั๊กอิน Google Services Gradle:apply plugin: 'com.android.application' // Add the following line: apply plugin: 'com.google.gms.google-services' // Google Services plugin android { // ... }
เพิ่ม Firebase SDK ให้กับแอปของคุณ
ใช้ Firebase Android BoM ประกาศการพึ่งพาไลบรารี Firebase Cloud Messaging Android ใน ไฟล์ Gradle ของโมดูล (ระดับแอป) (โดยปกติ
app/build.gradle
)เพื่อประสบการณ์ที่ดีที่สุดกับ 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:30.1.0') // Declare 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 { // Declare 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.0.6' implementation 'com.google.firebase:firebase-analytics:21.0.0' }
Kotlin+KTX
dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:30.1.0') // Declare 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 { // Declare 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.0.6' implementation 'com.google.firebase:firebase-analytics-ktx:21.0.0' }
ซิงค์แอปของคุณเพื่อให้แน่ใจว่าการขึ้นต่อกันทั้งหมดมีเวอร์ชันที่จำเป็น
Gradle บิลด์ที่ใช้ปลั๊กอิน Android Gradle (AGP) v4.2 หรือเก่ากว่านั้นจำเป็นต้องเปิดใช้งานการรองรับ Java 8 มิฉะนั้น โปรเจ็กต์ Android เหล่านี้จะเกิดความล้มเหลวในการสร้างเมื่อเพิ่ม Firebase SDK
ในการแก้ไขความล้มเหลวของบิลด์นี้ คุณสามารถทำตามหนึ่งในสองตัวเลือก:
- เพิ่ม
compileOptions
ที่อยู่ในรายการจากข้อความแสดงข้อผิดพลาดไปยังไฟล์build.gradle
ระดับแอป ของคุณ - เพิ่ม
minSdkVersion
สำหรับโครงการ Android ของคุณเป็น 26 หรือสูงกว่า
เรียนรู้เพิ่มเติมเกี่ยวกับความล้มเหลวในการสร้าง นี้ในคำถามที่พบบ่อย นี้
- เพิ่ม
สมัครสมาชิกแอพไคลเอนต์ในหัวข้อ
แอปไคลเอนต์สามารถสมัครรับหัวข้อที่มีอยู่หรือสร้างหัวข้อใหม่ได้ เมื่อแอปไคลเอ็นต์สมัครรับชื่อหัวข้อใหม่ (ชื่อที่ไม่มีอยู่ในโปรเจ็กต์ Firebase ของคุณ) หัวข้อใหม่ของชื่อนั้นจะถูกสร้างขึ้นใน FCM และไคลเอ็นต์ใดๆ ก็สามารถสมัครรับข้อมูลได้ในภายหลัง
หากต้องการสมัครรับหัวข้อ แอปไคลเอ็นต์จะเรียก Firebase Cloud Messaging subscribeToTopic()
ด้วยชื่อหัวข้อ FCM เมธอดนี้ส่งคืน Task
ซึ่งสามารถใช้โดยผู้ฟังที่สมบูรณ์เพื่อพิจารณาว่าการสมัครรับข้อมูลสำเร็จหรือไม่:
Java
FirebaseMessaging.getInstance().subscribeToTopic("weather") .addOnCompleteListener(new OnCompleteListener<Void>() { @Override public void onComplete(@NonNull Task<Void> task) { String msg = "Subscribed"; if (!task.isSuccessful()) { msg = "Subscribe failed"; } Log.d(TAG, msg); Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); } });
Kotlin+KTX
Firebase.messaging.subscribeToTopic("weather") .addOnCompleteListener { task -> var msg = "Subscribed" if (!task.isSuccessful) { msg = "Subscribe failed" } Log.d(TAG, msg) Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show() }
หากต้องการยกเลิกการสมัคร แอปไคลเอ็นต์จะเรียก Firebase Cloud Messaging unsubscribeFromTopic()
ด้วยชื่อหัวข้อ
รับและจัดการข้อความหัวข้อ
FCM ส่งข้อความหัวข้อในลักษณะเดียวกับข้อความปลายทางอื่นๆ
หากต้องการรับข้อความ ให้ใช้บริการที่ขยาย FirebaseMessagingService บริการของคุณควรแทนที่การเรียกกลับ onMessageReceived
และ onDeletedMessages
ควรจัดการข้อความภายใน 20 วินาทีหลังจากได้รับ (10 วินาทีใน Android Marshmallow) กรอบเวลาอาจสั้นลงขึ้นอยู่กับความล่าช้าของระบบปฏิบัติการที่เกิดขึ้นก่อนการโทรบน onMessageReceived
หลังจากเวลานั้น ลักษณะการทำงานของระบบปฏิบัติการต่างๆ เช่น ขีดจำกัดการดำเนินการในเบื้องหลัง ของ Android O อาจรบกวนการทำงานของคุณให้เสร็จสมบูรณ์ สำหรับข้อมูลเพิ่มเติม โปรดดูภาพรวมเกี่ยวกับ ลำดับความสำคัญของข้อความ
onMessageReceived
มีไว้สำหรับข้อความส่วนใหญ่ โดยมีข้อยกเว้นดังต่อไปนี้:
ข้อความแจ้งเตือนที่ส่งเมื่อแอปของคุณอยู่ในพื้นหลัง ในกรณีนี้ การแจ้งเตือนจะถูกส่งไปยังถาดระบบของอุปกรณ์ ผู้ใช้แตะที่การแจ้งเตือนจะเปิดตัวเรียกใช้งานแอปตามค่าเริ่มต้น
ข้อความที่มีทั้งการแจ้งเตือนและข้อมูล เมื่อได้รับในพื้นหลัง ในกรณีนี้ การแจ้งเตือนจะถูกส่งไปยังซิสเต็มเทรย์ของอุปกรณ์ และเพย์โหลดข้อมูลจะถูกส่งไปยังส่วนเพิ่มเติมของเจตนาของกิจกรรมตัวเรียกใช้งานของคุณ
สรุป:
สถานะของแอป | การแจ้งเตือน | ข้อมูล | ทั้งคู่ |
---|---|---|---|
เบื้องหน้า | onMessageReceived | onMessageReceived | onMessageReceived |
พื้นหลัง | ถาดระบบ | onMessageReceived | การแจ้งเตือน: ถาดระบบ ข้อมูล: ในส่วนเพิ่มเติมของเจตนา |
แก้ไขรายการแอป
ในการใช้ FirebaseMessagingService
คุณต้องเพิ่มสิ่งต่อไปนี้ในรายการแอปของคุณ:
<service android:name=".java.MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT" /> </intent-filter> </service>
นอกจากนี้ ขอแนะนำให้คุณตั้งค่าเริ่มต้นเพื่อปรับแต่งลักษณะที่ปรากฏของการแจ้งเตือน คุณสามารถระบุไอคอนเริ่มต้นแบบกำหนดเองและสีเริ่มต้นแบบกำหนดเองที่ใช้เมื่อไม่ได้ตั้งค่าที่เทียบเท่าในเพย์โหลดการแจ้งเตือน
เพิ่มบรรทัดเหล่านี้ในแท็ก application
เพื่อตั้งค่าไอคอนเริ่มต้นแบบกำหนดเองและสีที่กำหนดเอง:
<!-- Set custom default icon. This is used when no icon is set for incoming notification messages. See README(https://goo.gl/l4GJaQ) for more. --> <meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="@drawable/ic_stat_ic_notification" /> <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming notification message. See README(https://goo.gl/6BKBk7) for more. --> <meta-data android:name="com.google.firebase.messaging.default_notification_color" android:resource="@color/colorAccent" />
Android แสดงไอคอนเริ่มต้นที่กำหนดเองสำหรับ
- ข้อความแจ้งเตือนทั้งหมดที่ส่งจากผู้ แต่งการแจ้งเตือน
- ข้อความแจ้งเตือนใดๆ ที่ไม่ได้ตั้งค่าไอคอนไว้อย่างชัดเจนในส่วนข้อมูลการแจ้งเตือน
Android ใช้สีเริ่มต้นที่กำหนดเองสำหรับ
- ข้อความแจ้งเตือนทั้งหมดที่ส่งจากผู้ แต่งการแจ้งเตือน
- ข้อความแจ้งเตือนใดๆ ที่ไม่ได้กำหนดสีไว้อย่างชัดเจนในเพย์โหลดการแจ้งเตือน
หากไม่มีการตั้งค่าไอคอนเริ่มต้นที่กำหนดเองและไม่ได้ตั้งค่าไอคอนในส่วนข้อมูลการแจ้งเตือน Android จะแสดงไอคอนแอปพลิเคชันที่แสดงเป็นสีขาว
แทนที่ onMessageReceived
โดยการแทนที่วิธีการ FirebaseMessagingService.onMessageReceived
คุณสามารถดำเนินการตามวัตถุ RemoteMessage ที่ได้รับและรับข้อมูลข้อความ:
Java
@Override public void onMessageReceived(RemoteMessage remoteMessage) { // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.d(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); if (/* Check if data needs to be processed by long running job */ true) { // For long-running tasks (10 seconds or more) use WorkManager. scheduleJob(); } else { // Handle message within 10 seconds handleNow(); } } // Check if message contains a notification payload. if (remoteMessage.getNotification() != null) { Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody()); } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. }
Kotlin+KTX
override fun onMessageReceived(remoteMessage: RemoteMessage) { // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.d(TAG, "From: ${remoteMessage.from}") // Check if message contains a data payload. if (remoteMessage.data.isNotEmpty()) { Log.d(TAG, "Message data payload: ${remoteMessage.data}") if (/* Check if data needs to be processed by long running job */ true) { // For long-running tasks (10 seconds or more) use WorkManager. scheduleJob() } else { // Handle message within 10 seconds handleNow() } } // Check if message contains a notification payload. remoteMessage.notification?.let { Log.d(TAG, "Message Notification Body: ${it.body}") } // Also if you intend on generating your own notifications as a result of a received FCM // message, here is where that should be initiated. See sendNotification method below. }
แทนที่ onDeletedMessages
ในบางสถานการณ์ FCM อาจไม่ส่งข้อความ กรณีนี้เกิดขึ้นเมื่อมีข้อความที่รอดำเนินการมากเกินไป (>100) สำหรับแอปของคุณบนอุปกรณ์เฉพาะในขณะที่เชื่อมต่อ หรือหากอุปกรณ์ไม่ได้เชื่อมต่อกับ FCM เป็นเวลานานกว่าหนึ่งเดือน ในกรณีเหล่านี้ คุณอาจได้รับการเรียกกลับไปยัง FirebaseMessagingService.onDeletedMessages()
เมื่ออินสแตนซ์ของแอปได้รับการเรียกกลับนี้ อินสแตนซ์ควรทำการซิงค์อย่างสมบูรณ์กับเซิร์ฟเวอร์แอปของคุณ หากคุณไม่ได้ส่งข้อความไปยังแอปบนอุปกรณ์นั้นภายใน 4 สัปดาห์ที่ผ่านมา FCM จะไม่เรียก onDeletedMessages()
จัดการข้อความแจ้งเตือนในแอพพื้นหลัง
เมื่อแอปของคุณอยู่ในพื้นหลัง Android จะส่งข้อความแจ้งเตือนไปยังซิสเต็มเทรย์ ผู้ใช้แตะที่การแจ้งเตือนจะเปิดตัวเรียกใช้งานแอปตามค่าเริ่มต้น
ซึ่งรวมถึงข้อความที่มีทั้งส่วนของการแจ้งเตือนและข้อมูล (และข้อความทั้งหมดที่ส่งจากคอนโซลการแจ้งเตือน) ในกรณีเหล่านี้ การแจ้งเตือนจะถูกส่งไปยังซิสเต็มเทรย์ของอุปกรณ์ และเพย์โหลดข้อมูลจะถูกส่งในส่วนเพิ่มเติมของเจตนาของกิจกรรมตัวเรียกใช้งานของคุณ
สำหรับข้อมูลเชิงลึกเกี่ยวกับการส่งข้อความไปยังแอปของคุณ โปรดดู แดชบอร์ดการรายงาน FCM ซึ่งบันทึกจำนวนข้อความที่ส่งและเปิดบนอุปกรณ์ Apple และ Android พร้อมด้วยข้อมูลสำหรับ "การแสดงผล" (การแจ้งเตือนที่ผู้ใช้เห็น) สำหรับแอป Android
แอปที่จำกัดในเบื้องหลัง (Android P หรือใหม่กว่า)
FCM อาจไม่ส่งข้อความไปยังแอปที่ถูก จำกัดการใช้งานเบื้องหลัง โดยผู้ใช้ (เช่น ผ่าน: การตั้งค่า -> แอปและการแจ้งเตือน -> [ชื่อแอป] -> แบตเตอรี่) เมื่อแอปของคุณถูกลบออกจากการจำกัดพื้นหลังแล้ว ข้อความใหม่ไปยังแอปจะถูกส่งเหมือนเดิม เพื่อป้องกันข้อความที่สูญหายและผลกระทบจากการจำกัดพื้นหลังอื่นๆ ให้หลีกเลี่ยงพฤติกรรมที่ไม่ดีตามรายการของความพยายามของ Android Vitals ลักษณะการทำงานเหล่านี้อาจทำให้อุปกรณ์ Android แนะนำให้ผู้ใช้ทราบว่าแอปของคุณถูกจำกัดการทำงานในเบื้องหลัง แอปของคุณสามารถตรวจสอบได้ว่ามีการจำกัดพื้นหลังโดยใช้: isBackgroundRestricted()สร้างคำขอส่ง
หลังจากที่คุณสร้างหัวข้อแล้ว ไม่ว่าจะสมัครใช้งานอินสแตนซ์แอปไคลเอ็นต์ในหัวข้อที่ฝั่งไคลเอ็นต์หรือผ่าน API ของเซิร์ฟเวอร์ คุณจะส่งข้อความไปยังหัวข้อได้ หากนี่เป็นครั้งแรกที่คุณสร้างส่งคำขอสำหรับ FCM โปรดดูคำแนะนำเกี่ยวกับ สภาพแวดล้อมเซิร์ฟเวอร์ของคุณและ FCM สำหรับข้อมูลเบื้องหลังและการตั้งค่าที่สำคัญ
ในตรรกะการส่งของคุณบนแบ็กเอนด์ ให้ระบุชื่อหัวข้อที่ต้องการดังที่แสดง:
Node.js
// The topic name can be optionally prefixed with "/topics/".
const topic = 'highScores';
const message = {
data: {
score: '850',
time: '2:45'
},
topic: topic
};
// Send a message to devices subscribed to the provided topic.
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Java
// The topic name can be optionally prefixed with "/topics/".
String topic = "highScores";
// See documentation on defining a message payload.
Message message = Message.builder()
.putData("score", "850")
.putData("time", "2:45")
.setTopic(topic)
.build();
// Send a message to the devices subscribed to the provided topic.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
Python
# The topic name can be optionally prefixed with "/topics/".
topic = 'highScores'
# See documentation on defining a message payload.
message = messaging.Message(
data={
'score': '850',
'time': '2:45',
},
topic=topic,
)
# Send a message to the devices subscribed to the provided topic.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
ไป
// The topic name can be optionally prefixed with "/topics/".
topic := "highScores"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Topic: topic,
}
// Send a message to the devices subscribed to the provided topic.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
ค#
// The topic name can be optionally prefixed with "/topics/".
var topic = "highScores";
// See documentation on defining a message payload.
var message = new Message()
{
Data = new Dictionary<string, string>()
{
{ "score", "850" },
{ "time", "2:45" },
},
Topic = topic,
};
// Send a message to the devices subscribed to the provided topic.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
พักผ่อน
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"topic" : "foo-bar",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message"
}
}
}
คำสั่ง cURL:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"message": {
"topic" : "foo-bar",
"notification": {
"body": "This is a Firebase Cloud Messaging Topic Message!",
"title": "FCM Message"
}
}
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
ในการส่งข้อความไปยังหัวข้อต่างๆ รวมกัน ให้ระบุ เงื่อนไข ซึ่งเป็นนิพจน์บูลีนที่ระบุหัวข้อเป้าหมาย ตัวอย่างเช่น เงื่อนไขต่อไปนี้จะส่งข้อความไปยังอุปกรณ์ที่สมัครใช้ TopicA
และ TopicB
หรือ TopicC
:
"'TopicA' in topics && ('TopicB' in topics || 'TopicC' in topics)"
FCM จะประเมินเงื่อนไขใดๆ ในวงเล็บก่อน จากนั้นจึงประเมินนิพจน์จากซ้ายไปขวา ในนิพจน์ข้างต้น ผู้ใช้ที่สมัครรับข่าวสารในหัวข้อเดียวจะไม่ได้รับข้อความ ในทำนองเดียวกัน ผู้ใช้ที่ไม่ได้สมัครใช้ TopicA
จะไม่ได้รับข้อความ ชุดค่าผสมเหล่านี้ได้รับ:
-
TopicA
และTopicB
-
TopicA
และTopicC
คุณสามารถรวมหัวข้อได้ถึงห้าหัวข้อในนิพจน์เงื่อนไขของคุณ
ในการส่งไปยังเงื่อนไข:
Node.js
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
const condition = '\'stock-GOOG\' in topics || \'industry-tech\' in topics';
// See documentation on defining a message payload.
const message = {
notification: {
title: '$FooCorp up 1.43% on the day',
body: '$FooCorp gained 11.80 points to close at 835.67, up 1.43% on the day.'
},
condition: condition
};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
getMessaging().send(message)
.then((response) => {
// Response is a message ID string.
console.log('Successfully sent message:', response);
})
.catch((error) => {
console.log('Error sending message:', error);
});
Java
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
String condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
Message message = Message.builder()
.setNotification(Notification.builder()
.setTitle("$GOOG up 1.43% on the day")
.setBody("$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.")
.build())
.setCondition(condition)
.build();
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
String response = FirebaseMessaging.getInstance().send(message);
// Response is a message ID string.
System.out.println("Successfully sent message: " + response);
Python
# Define a condition which will send to devices which are subscribed
# to either the Google stock or the tech industry topics.
condition = "'stock-GOOG' in topics || 'industry-tech' in topics"
# See documentation on defining a message payload.
message = messaging.Message(
notification=messaging.Notification(
title='$GOOG up 1.43% on the day',
body='$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.',
),
condition=condition,
)
# Send a message to devices subscribed to the combination of topics
# specified by the provided condition.
response = messaging.send(message)
# Response is a message ID string.
print('Successfully sent message:', response)
ไป
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
condition := "'stock-GOOG' in topics || 'industry-tech' in topics"
// See documentation on defining a message payload.
message := &messaging.Message{
Data: map[string]string{
"score": "850",
"time": "2:45",
},
Condition: condition,
}
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
response, err := client.Send(ctx, message)
if err != nil {
log.Fatalln(err)
}
// Response is a message ID string.
fmt.Println("Successfully sent message:", response)
ค#
// Define a condition which will send to devices which are subscribed
// to either the Google stock or the tech industry topics.
var condition = "'stock-GOOG' in topics || 'industry-tech' in topics";
// See documentation on defining a message payload.
var message = new Message()
{
Notification = new Notification()
{
Title = "$GOOG up 1.43% on the day",
Body = "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day.",
},
Condition = condition,
};
// Send a message to devices subscribed to the combination of topics
// specified by the provided condition.
string response = await FirebaseMessaging.DefaultInstance.SendAsync(message);
// Response is a message ID string.
Console.WriteLine("Successfully sent message: " + response);
พักผ่อน
POST https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
Content-Type: application/json
Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA
{
"message":{
"condition": "'dogs' in topics || 'cats' in topics",
"notification" : {
"body" : "This is a Firebase Cloud Messaging Topic Message!",
"title" : "FCM Message",
}
}
}
คำสั่ง cURL:
curl -X POST -H "Authorization: Bearer ya29.ElqKBGN2Ri_Uz...HnS_uNreA" -H "Content-Type: application/json" -d '{
"notification": {
"title": "FCM Message",
"body": "This is a Firebase Cloud Messaging Topic Message!",
},
"condition": "'dogs' in topics || 'cats' in topics"
}' https://fcm.googleapis.com/v1/projects/myproject-b5ae1/messages:send HTTP/1.1
ขั้นตอนถัดไป
- คุณสามารถใช้เซิร์ฟเวอร์ของคุณเพื่อสมัครใช้งานอินสแตนซ์แอพไคลเอนต์ตามหัวข้อและดำเนินการจัดการอื่นๆ ดู จัดการการสมัครหัวข้อบนเซิร์ฟเวอร์
- เรียนรู้เพิ่มเติมเกี่ยวกับวิธีอื่นในการส่งไปยังอุปกรณ์หลายเครื่อง — การส่งข้อความกลุ่มอุปกรณ์