push-notification-setup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Push Notification Setup

推送通知设置

Implement push notifications across mobile and web platforms.
在移动和Web平台实现推送通知功能。

Firebase Cloud Messaging (React Native)

Firebase Cloud Messaging (React Native)

javascript
import messaging from '@react-native-firebase/messaging';

// Request permission
async function requestPermission() {
  const status = await messaging().requestPermission();
  if (status === messaging.AuthorizationStatus.AUTHORIZED) {
    const token = await messaging().getToken();
    await sendTokenToServer(token);
  }
}

// Handle foreground messages
messaging().onMessage(async message => {
  console.log('Foreground message:', message);
  showLocalNotification(message);
});

// Handle background/quit messages
messaging().setBackgroundMessageHandler(async message => {
  console.log('Background message:', message);
});

// Handle token refresh
messaging().onTokenRefresh(token => {
  sendTokenToServer(token);
});
javascript
import messaging from '@react-native-firebase/messaging';

// Request permission
async function requestPermission() {
  const status = await messaging().requestPermission();
  if (status === messaging.AuthorizationStatus.AUTHORIZED) {
    const token = await messaging().getToken();
    await sendTokenToServer(token);
  }
}

// Handle foreground messages
messaging().onMessage(async message => {
  console.log('Foreground message:', message);
  showLocalNotification(message);
});

// Handle background/quit messages
messaging().setBackgroundMessageHandler(async message => {
  console.log('Background message:', message);
});

// Handle token refresh
messaging().onTokenRefresh(token => {
  sendTokenToServer(token);
});

iOS Native (Swift)

iOS Native (Swift)

swift
import UserNotifications

func requestAuthorization() {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
        if granted {
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    sendTokenToServer(token)
}
swift
import UserNotifications

func requestAuthorization() {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
        if granted {
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    sendTokenToServer(token)
}

Android (Kotlin)

Android (Kotlin)

kotlin
class MyFirebaseService : FirebaseMessagingService() {
    override fun onNewToken(token: String) {
        sendTokenToServer(token)
    }

    override fun onMessageReceived(message: RemoteMessage) {
        message.notification?.let {
            showNotification(it.title, it.body)
        }
    }

    private fun showNotification(title: String?, body: String?) {
        val channelId = "default"
        val notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.drawable.ic_notification)
            .build()

        NotificationManagerCompat.from(this).notify(0, notification)
    }
}
kotlin
class MyFirebaseService : FirebaseMessagingService() {
    override fun onNewToken(token: String) {
        sendTokenToServer(token)
    }

    override fun onMessageReceived(message: RemoteMessage) {
        message.notification?.let {
            showNotification(it.title, it.body)
        }
    }

    private fun showNotification(title: String?, body: String?) {
        val channelId = "default"
        val notification = NotificationCompat.Builder(this, channelId)
            .setContentTitle(title)
            .setContentText(body)
            .setSmallIcon(R.drawable.ic_notification)
            .build()

        NotificationManagerCompat.from(this).notify(0, notification)
    }
}

Best Practices

最佳实践

  • Request permission at appropriate time
  • Handle token refresh
  • Support notification channels (Android)
  • Implement deep linking
  • Never send sensitive data in payload
  • Test on real devices
  • 在合适的时机请求权限
  • 处理Token刷新
  • 支持通知渠道(Android)
  • 实现深度链接
  • 切勿在消息载荷中发送敏感数据
  • 在真实设备上测试