Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีส่งข้อความจาก Firebase Console หลังสร้างโปรเจกต์

ภาพรวม

คู่มือทีละขั้นตอนสำหรับการส่ง Push Notification ผ่าน Firebase Console (Firebase Cloud Messaging) หลังจากสร้างโปรเจกต์เสร็จแล้ว

ขั้นตอนการส่ง Notification

1. เข้าสู่ Firebase Console

เปิด https://console.firebase.google.com/ และล็อกอินด้วย Google Account

2. เลือกโปรเจกต์

คลิกเลือกโปรเจกต์ที่ต้องการส่งการแจ้งเตือน (เช่น "tutorialspoint")

3. เข้าสู่เมนู Cloud Messaging

  • ในเมนูด้านซ้าย เลือก Engage → Messaging
  • หรือในรูปแบบเก่า: Grow → Cloud Messaging

4. สร้างแคมเปญใหม่

คลิกปุ่ม Create your first campaign หรือ New notification

5. กรอกข้อมูลข้อความ (Notification Composer)

Notification title: หัวข้อการแจ้งเตือน
Notification text: เนื้อหาข้อความ
Notification image (optional): รูปภาพประกอบ (URL)

6. กำหนด Target (เป้าหมาย)

  • Target: เลือกแอปพลิเคชัน (Android/iOS/Web)
  • Version: กรองตามเวอร์ชันแอป (ถ้าต้องการ)
  • User segment: กรองตามกลุ่มผู้ใช้ (Audiences)
  • Language: กรองตามภาษา

7. ตั้งค่าการส่ง (Scheduling)

  • Send now: ส่งทันที
  • Schedule for later: กำหนดวันที่/เวลาที่ต้องการส่ง
  • Time zone: เลือก Time zone

8. ตัวเลือกเพิ่มเติม (Additional Options)

  • Custom data: Key-Value pairs สำหรับส่งข้อมูลเพิ่มเติมไปยังแอป
  • Priority: High/Normal (ส่งผลต่อการส่งทันทีหรือรอ Doze mode)
  • Sound: เสียงการแจ้งเตือน
  • Expiration: ระยะเวลาหมดอายุของข้อความ

9. ตรวจสอบและส่ง (Review & Publish)

ตรวจสอบข้อมูลทั้งหมดในหน้า Review แล้วคลิก Publish เพื่อส่ง

ประเภทข้อความ (Message Types)

ประเภทคำอธิบายกรณีใช้งาน
Notification Messageแสดงการแจ้งเตือนอัตโนมัติ มี Title/BodyMarketing, General alerts
Data Messageส่งเฉพาะ Key-Value ไม่แสดง Notification เองBackground sync, Silent updates
Bothส่งทั้ง Notification และ Dataต้องการแสดงและประมวลผลข้อมูล

การส่งผ่าน Code (Server-side)

สำหรับการส่งแบบโปรแกรม ใช้ Firebase Admin SDK:

// Node.js Example
const admin = require('firebase-admin');
admin.initializeApp();

const message = {
    notification: {
        title: 'Hello',
        body: 'World'
    },
    token: registrationToken // หรือ topic: 'news'
};

admin.messaging().send(message)
    .then(response => console.log('Sent:', response))
    .catch(error => console.error('Error:', error));

ข้อกำหนดก่อนส่ง

  • เพิ่ม google-services.json ในโปรเจกต์ Android
  • เพิ่ม Dependency: implementation 'com.google.firebase:firebase-messaging:23.1.0'
  • สร้าง Service ขยาย FirebaseMessagingService เพื่อรับข้อความ
  • ขอสิทธิ์ POST_NOTIFICATIONS (Android 13+)