it

Push Notification คืออะไร? สอนสร้างระบบ Push และ Real-time สำหรับ Mobile App 2026

push notifications realtime mobile guide
Push Notification คืออะไร? สอนสร้างระบบ Push และ Real-time สำหรับ Mobile App 2026

Push Notification เป็นช่องทางสำคัญที่สุดในการดึงผู้ใช้กลับมาใช้แอปอีกครั้ง ในปี 2026 แอปที่ส่ง Push Notification อย่างชาญฉลาดมี Retention Rate สูงกว่าแอปที่ไม่ส่งถึง 3-10 เท่า แต่ถ้าส่งมากเกินไปหรือไม่ตรงเป้าหมาย ผู้ใช้จะปิด Notification หรือถอนการติดตั้งแอปทันที การออกแบบระบบ Push Notification และ Real-time ที่ดีจึงเป็นทักษะที่ Mobile Developer ต้องมี

บทความนี้จะพาคุณเข้าใจ Push Notification ตั้งแต่พื้นฐานจนถึง Implementation จริง ครอบคลุม FCM, APNs, Rich Notification, Deep Linking, Server-side Push, Real-time Features ด้วย WebSocket และ Firebase Realtime Database สำหรับผู้ที่ต้องการเข้าใจ Architecture ของ Mobile App ก่อน แนะนำอ่าน คู่มือ Mobile App Architecture ประกอบ

อ่านเพิ่ม: NestJS คืออะไร? Enterprise-grade Node.js Framework สำหรับ Ba · อ่านเพิ่ม: Zod คืออะไร? สอน Runtime Type Validation สำหรับ TypeScript D · อ่านเพิ่ม: Edge Computing คืออะไร? สอนสร้าง Edge Application ด้วย Cloud

ประเภทของ Push Notification

Push Notification คืออะไร? สอนสร้างระบบ Push และ Real-time สำหรับ Mobile App 2026

Push Notification แบ่งออกเป็น 4 ประเภทหลัก แต่ละประเภทมีจุดประสงค์และวิธีจัดการที่แตกต่างกัน

1. Remote Push Notification

เป็น Notification ที่ส่งจาก Server ผ่าน Push Service (FCM / APNs) ไปยังอุปกรณ์ของผู้ใช้ ใช้สำหรับแจ้งเตือนข้อความใหม่ ข่าว โปรโมชั่น หรือ Event สำคัญ เป็นประเภทที่ใช้มากที่สุดในแอปทั่วไป

เนื้อหาเกี่ยวข้อง — ดูเพิ่มเติมเรื่อง cloud pc gaming — ข้อมูลครบถ้วน 2026

2. Local Notification

สร้างจากภายในแอปเอง ไม่ต้องผ่าน Server เหมาะสำหรับ Reminder, Alarm, ตั้งเวลาเตือน หรือแจ้งเตือนเมื่อทำ Task บางอย่างเสร็จ ทำงานได้แม้ไม่มี Internet

3. Rich Notification

Notification ที่แสดงเนื้อหามากกว่าแค่ข้อความ เช่น รูปภาพ ปุ่ม Action วิดีโอ หรือ UI แบบ Expandable ช่วยเพิ่ม Engagement ได้มากกว่า Text-only Notification

แนะนำเพิ่มเติม — คู่มือเทรดจาก SiamCafeBook

4. Silent Notification (Data-only)

Notification ที่ส่งมาแบบเงียบๆ ไม่แสดงอะไรบนหน้าจอ แต่ปลุกแอปให้ทำงานเบื้องหลัง เช่น Sync ข้อมูล อัพเดต Cache หรือเตรียมข้อมูลสำหรับการใช้งานครั้งต่อไป

ประเภทต้องการ Serverต้องการ Internetแสดง UIUse Case
Remote Pushใช่ใช่ใช่ข้อความ, ข่าว, โปรโมชั่น
Localไม่ไม่ใช่Reminder, Alarm, Timer
Richใช่ใช่ใช่ (พร้อมสื่อ)ข่าว+รูป, ปุ่ม Action
Silentใช่ใช่ไม่Data Sync, Cache Update

FCM (Firebase Cloud Messaging) — Setup

FCM เป็น Push Service ของ Google ที่ใช้ส่ง Notification ไปยังทั้ง Android และ iOS (ผ่าน APNs) รองรับทั้ง Individual, Topic-based และ Conditional messaging เป็นมาตรฐานที่ใช้มากที่สุดในปี 2026

เนื้อหาเกี่ยวข้อง — แนะนำให้อ่าน WordPress Block Theme Developer Experience DX

Notification Channels (Android) และ Categories (iOS)

ตั้งแต่ Android 8.0 (API 26) ทุกแอปต้องสร้าง Notification Channel เพื่อให้ผู้ใช้ควบคุมการแจ้งเตือนได้ละเอียดขึ้น ส่วน iOS ใช้ Categories สำหรับจัดกลุ่ม Action

// iOS — Notification Categories + Actions
func registerNotificationCategories() {
    // Action: ตอบกลับ
    let replyAction = UNTextInputNotificationAction(
        identifier: "REPLY_ACTION",
        title: "ตอบกลับ",
        options: [],
        textInputButtonTitle: "ส่ง",
        textInputPlaceholder: "พิมพ์ข้อความ..."
    )

    // Action: Like
    let likeAction = UNNotificationAction(
        identifier: "LIKE_ACTION",
        title: "ถูกใจ",
        options: []
    )

    // Action: Mark as Read
    let readAction = UNNotificationAction(
        identifier: "MARK_READ_ACTION",
        title: "อ่านแล้ว",
        options: .destructive
    )

    // Category: Chat Message
    let chatCategory = UNNotificationCategory(
        identifier: "CHAT_MESSAGE",
        actions: [replyAction, likeAction, readAction],
        intentIdentifiers: [],
        options: .customDismissAction
    )

    UNUserNotificationCenter.current().setNotificationCategories([chatCategory])
}

Notification Payload Structure

การออกแบบ Payload ที่ดีเป็นกุญแจสำคัญ FCM รองรับ 2 ประเภท Payload คือ notification (แสดงอัตโนมัติ) และ data (จัดการเอง) แนะนำให้ใช้ data-only เสมอเพื่อควบคุมการแสดงผลได้เต็มที่

// Notification Payload — แสดงอัตโนมัติ (ควบคุมน้อย)
{
  "message": {
    "token": "device-fcm-token",
    "notification": {
      "title": "ข้อความใหม่",
      "body": "สวัสดีครับ มีอะไรอัพเดตบ้าง?"
    }
  }
}

// Data-only Payload — ควบคุมเต็มที่ (แนะนำ)
{
  "message": {
    "token": "device-fcm-token",
    "data": {
      "type": "chat_message",
      "title": "ข้อความจาก John",
      "body": "สวัสดีครับ มีอะไรอัพเดตบ้าง?",
      "sender_id": "user-123",
      "chat_id": "chat-456",
      "sender_avatar": "https://example.com/avatar.jpg",
      "timestamp": "2026-04-10T14:30:00Z",
      "deep_link": "myapp://chat/chat-456"
    },
    "android": {
      "priority": "high"
    },
    "apns": {
      "payload": {
        "aps": {
          "content-available": 1
        }
      },
      "headers": {
        "apns-priority": "10"
      }
    }
  }
}
Data-only vs Notification Payload: ใช้ Data-only Payload เสมอเมื่อต้องการควบคุมการแสดง Notification เช่น แสดงรูปภาพ Deep Link หรือ Custom UI เพราะ Notification Payload จะถูก System จัดการอัตโนมัติซึ่งควบคุมไม่ได้ สำหรับแนวทางออกแบบ API เพิ่มเติม ดูที่ คู่มือ API Design

Topic-based Notifications

Topic-based Notification ช่วยให้คุณส่ง Push ไปยังกลุ่มผู้ใช้ที่สนใจเรื่องเดียวกัน โดยไม่ต้องเก็บ Token ของทุกคน

แนะนำเพิ่มเติม — แหล่งความรู้ Forex iCafeForex

Token Management

Token Management เป็นหัวใจของระบบ Push Notification เพราะ FCM Token สามารถเปลี่ยนได้ตลอดเวลา (อัพเดตแอป ล้างข้อมูล เปลี่ยนอุปกรณ์) ถ้าไม่จัดการดี จะส่ง Push ไม่ถึงหรือส่งไปอุปกรณ์ที่ไม่มีแอปแล้ว

เนื้อหาเกี่ยวข้อง — อ่านต่อ: Cloudflare R2 High Availability HA Setup

Deep Linking จาก Notification

Push Notification คืออะไร? สอนสร้างระบบ Push และ Real-time สำหรับ Mobile App 2026

Deep Linking ช่วยให้ผู้ใช้กด Notification แล้วไปถึงหน้าจอที่ถูกต้องทันที ไม่ใช่ไปหน้า Home แล้วต้องนำทางเอง สำหรับเรื่อง WebSocket และ Real-time ที่เกี่ยวข้อง ดูที่ คู่มือ WebSocket

Rich Notifications

Rich Notification เพิ่ม Engagement ได้มากกว่า Text-only Notification ถึง 56% ตามสถิติปี 2026 รองรับรูปภาพ ปุ่ม Action และ Expandable Content

Android — Rich Notification

// Big Picture Style (แสดงรูปภาพ)
fun showRichNotification(title: String, body: String, imageUrl: String) {
    // โหลดรูปภาพก่อน
    val bitmap = Glide.with(context)
        .asBitmap()
        .load(imageUrl)
        .submit()
        .get()

    val notification = NotificationCompat.Builder(context, "general")
        .setSmallIcon(R.drawable.ic_notification)
        .setContentTitle(title)
        .setContentText(body)
        .setLargeIcon(bitmap)
        .setStyle(
            NotificationCompat.BigPictureStyle()
                .bigPicture(bitmap)
                .bigLargeIcon(null as Bitmap?)
        )
        // Action Buttons
        .addAction(R.drawable.ic_reply, "ตอบกลับ", replyPendingIntent)
        .addAction(R.drawable.ic_like, "ถูกใจ", likePendingIntent)
        .setAutoCancel(true)
        .build()

    NotificationManagerCompat.from(context).notify(notificationId, notification)
}

// Messaging Style (สำหรับ Chat)
fun showChatNotification(messages: List<ChatMessage>) {
    val person = Person.Builder()
        .setName(messages.first().senderName)
        .setIcon(IconCompat.createWithBitmap(avatarBitmap))
        .build()

    val style = NotificationCompat.MessagingStyle(person)
        .setConversationTitle("กลุ่ม Developer Thailand")

    messages.forEach { msg ->
        style.addMessage(msg.text, msg.timestamp, person)
    }

    val notification = NotificationCompat.Builder(context, "chat_messages")
        .setSmallIcon(R.drawable.ic_chat)
        .setStyle(style)
        .setCategory(NotificationCompat.CATEGORY_MESSAGE)
        .build()

    NotificationManagerCompat.from(context).notify(chatId, notification)
}

Silent Notifications — Background Data Sync

// Android — Data-only Message (Background)
override fun onMessageReceived(message: RemoteMessage) {
    if (message.data["type"] == "data_sync") {
        // Sync ข้อมูลเบื้องหลัง ไม่แสดง Notification
        CoroutineScope(Dispatchers.IO).launch {
            val syncType = message.data["sync_type"]
            when (syncType) {
                "products" -> productRepository.syncFromServer()
                "settings" -> settingsRepository.refreshSettings()
                "messages" -> messageRepository.fetchNewMessages()
            }
        }
    }
}

// iOS — Silent Push (content-available)
// Server Payload:
// {
//   "aps": { "content-available": 1 },
//   "sync_type": "products"
// }

func application(_ application: UIApplication,
                 didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler:
                 @escaping (UIBackgroundFetchResult) -> Void) {
    let syncType = userInfo["sync_type"] as? String ?? ""

    Task {
        do {
            switch syncType {
            case "products":
                try await ProductRepository.shared.syncFromServer()
            case "settings":
                try await SettingsRepository.shared.refresh()
            default:
                break
            }
            completionHandler(.newData)
        } catch {
            completionHandler(.failed)
        }
    }
}

หลีกเลี่ยง Notification Fatigue

Notification Fatigue เกิดขึ้นเมื่อผู้ใช้ได้รับ Push Notification มากเกินไปจนเริ่มไม่สนใจ ปิด Notification หรือถอนการติดตั้งแอป กฎที่ต้องจำคือ ส่งน้อยแต่ตรงเป้า ดีกว่าส่งมากแต่ไม่ตรงใจ

  • จำกัดจำนวน: ไม่ส่งเกิน 3-5 ครั้งต่อวัน (ยกเว้น Chat Message)
  • Timing: ส่งในเวลาที่เหมาะสม ไม่ส่งตอนดึก (21:00-07:00) ใช้ Timezone ของผู้ใช้
  • Personalization: ส่งตามพฤติกรรมของผู้ใช้ ไม่ใช่ส่งแบบ Broadcast ทุกคน
  • Frequency Capping: ตั้งขีดจำกัดว่า User แต่ละคนรับ Push ได้กี่ครั้งต่อช่วงเวลา
  • Opt-in/Opt-out: ให้ผู้ใช้เลือกประเภท Notification ที่ต้องการรับ
  • A/B Testing: ทดสอบ Title, Body, Timing เพื่อหาสูตรที่ Open Rate สูงสุด

Real-time Features สำหรับ Mobile App

นอกจาก Push Notification แล้ว Real-time Features เป็นสิ่งที่ผู้ใช้คาดหวังในแอปสมัยใหม่ ไม่ว่าจะเป็น Chat, Live Updates, Real-time Collaboration หรือ Live Tracking สำหรับการเข้าใจ Event-driven Architecture ที่เป็นพื้นฐาน ดูที่ คู่มือ Event-driven Architecture

เนื้อหาเกี่ยวข้อง — MetalLB Load Balancer Architecture Design Pattern

Real-time + Push Combination Patterns

ในแอปจริง Real-time (WebSocket) และ Push Notification ทำงานร่วมกัน โดยมีหลักการว่า: เมื่อ App อยู่ Foreground ใช้ WebSocket เมื่อ App อยู่ Background ใช้ Push Notification

Testing Push Notifications

// ทดสอบ Push ด้วย Firebase CLI
// 1. ติดตั้ง Firebase CLI
npm install -g firebase-tools

// 2. ส่ง Test Push
firebase messaging:send --project your-project-id \
  --json '{
    "message": {
      "token": "device-token-here",
      "data": {
        "type": "test",
        "title": "ทดสอบ Push",
        "body": "นี่คือ Push ทดสอบ"
      }
    }
  }'

// Unit Test — Push Service
describe('PushNotificationService', () => {
  it('should send push to valid token', async () => {
    const mockSend = jest.spyOn(admin.messaging(), 'send')
      .mockResolvedValue('message-id-123');

    const result = await pushService.sendToDevice('valid-token', {
      type: 'test',
      title: 'Test',
      body: 'Test body',
    });

    expect(result.success).toBe(true);
    expect(mockSend).toHaveBeenCalledWith(
      expect.objectContaining({
        token: 'valid-token',
      })
    );
  });

  it('should remove invalid token', async () => {
    jest.spyOn(admin.messaging(), 'send')
      .mockRejectedValue({
        code: 'messaging/registration-token-not-registered',
      });

    const removeSpy = jest.spyOn(tokenService, 'removeInvalidToken');

    await pushService.sendToDevice('invalid-token', payload);

    expect(removeSpy).toHaveBeenCalledWith('invalid-token');
  });
});

Notification Permission Best Practices

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

  • Pre-permission Screen: แสดงหน้าจออธิบายว่า Notification จะส่งอะไร และประโยชน์ที่ได้รับ ก่อนที่จะขอ Permission จริง
  • Contextual Timing: ขอ Permission ตอนที่ผู้ใช้ทำสิ่งที่เกี่ยวข้อง เช่น หลังจากสั่งซื้อสินค้า (เพื่อแจ้งสถานะ) หรือหลังจากส่งข้อความ (เพื่อแจ้งเตือนตอบกลับ)
  • Gradual Permission: เริ่มจากขอ Permission น้อย แล้วค่อยขอเพิ่มตามการใช้งาน
  • Fallback: ถ้าผู้ใช้ปฏิเสธ ให้มี In-app Notification แทน

สรุป — Push Notification & Real-time Checklist

หัวข้อเทคโนโลยีคำแนะนำ
Push ServiceFCM + APNsใช้ FCM เป็นหลัก รองรับทั้ง Android + iOS
PayloadData-onlyใช้ Data-only เพื่อควบคุมการแสดงผลเต็มที่
Token ManagementServer-side DBRefresh Token สม่ำเสมอ ลบ Token หมดอายุ
Deep LinkingCustom URL Schemeทุก Push ต้องมี Deep Link ไปหน้าจอที่ถูกต้อง
Rich NotificationBigPicture, Service Extensionเพิ่ม Engagement ด้วยรูปภาพและปุ่ม Action
Real-time ChatWebSocketใช้ WebSocket สำหรับ Chat, ส่งผ่าน Push เมื่อ Offline
Live DataSSE / Firebase RTDBSSE สำหรับ One-way, Firebase RTDB สำหรับ Sync
AnalyticsCustom + FirebaseTrack Sent, Delivered, Opened, CTR
FrequencyThrottling Serviceจำกัดจำนวน Push ต่อวัน/ชั่วโมง
PermissionPre-permission Screenอธิบายก่อนขอ ให้ทางเลือก Skip

Push Notification และ Real-time เป็นฟีเจอร์ที่ทำให้แอปมีชีวิต ผู้ใช้รู้สึกว่าแอปทำงานเพื่อเขาอยู่ตลอดเวลา แต่ถ้าใช้ไม่ดีจะเป็นดาบสองคม สิ่งสำคัญคือ ส่งสิ่งที่ผู้ใช้ต้องการ ในเวลาที่เหมาะสม ไปยังคนที่ใช่ สำหรับ Backend Architecture ที่เกี่ยวข้อง อ่านเพิ่มที่ คู่มือ TypeScript + Node.js และ คู่มือ Microservices

XM Legend · เทรดเดอร์ & ผู้สอน Forex 13 ปี

ผู้ก่อตั้ง SiamCafe ตั้งแต่ปี 1997 · เทรดเดอร์สาย Forex มากกว่า 13 ปี ได้รับการยกย่องเป็น XM Legend · แบ่งปันความรู้ Forex, ไอที, AI และการเทรด จากประสบการณ์จริงในตลาดจริง