You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何本地化Firebase发送的通知?需支持后台处理场景

解决方案:Firebase通知本地化(支持前后台)

我来帮你搞定这个问题——要在Firebase通知到达时(不管App处于前台还是后台)访问data对象并完成本地化翻译,核心是跳过系统默认的通知自动显示逻辑,自己接管通知的构建与展示。下面分平台给你具体实现方案:

核心思路

Firebase通知分两种类型:

  • 通知消息(Notification Payload):后台状态下由系统自动展示,无法在显示前修改内容;
  • 数据消息(Data Payload):无论前后台,都会直接传递到App的处理逻辑中,我们可以在这里拿到data里的翻译键,本地化后再自定义通知。

所以建议你用纯Data Payload发送通知,这样就能完全控制本地化流程。


1. Cloud Function 配置(发送纯Data Payload)

修改你的Cloud Function,只发送data字段,同时为iOS配置content-available以触发后台唤醒:

exports.sendLocalizedNotification = functions.https.onCall(async (data, context) => {
  const targetToken = data.token; // 目标设备Token
  const payload = {
    data: {
      "translatable_title_key": "notification_welcome", // 本地化键(不是具体文本)
      "translatable_body_key": "notification_content",
      "extra_data": "some_additional_info" // 其他业务数据
    },
    // iOS专属配置:唤醒后台处理
    apns: {
      payload: {
        aps: {
          "content-available": 1
        }
      }
    }
  };

  // 发送通知
  await admin.messaging().sendToDevice(targetToken, payload);
  return { success: true };
});

2. Android 端实现

通过FirebaseMessagingService接收Data消息,在onMessageReceived中处理本地化并构建通知:

步骤1:注册服务到Manifest

<service
    android:name=".MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>

步骤2:实现消息处理逻辑(Kotlin示例)

class MyFirebaseMessagingService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        super.onMessageReceived(remoteMessage)
        // 提取Data对象
        val data = remoteMessage.data
        val titleKey = data["translatable_title_key"] ?: return
        val bodyKey = data["translatable_body_key"] ?: return

        // 根据系统当前语言获取本地化文本
        val localizedTitle = getString(resources.getIdentifier(titleKey, "string", packageName))
        val localizedBody = getString(resources.getIdentifier(bodyKey, "string", packageName))

        // 构建自定义通知
        val notificationChannelId = "localized_notifications"
        val notificationBuilder = NotificationCompat.Builder(this, notificationChannelId)
            .setSmallIcon(R.drawable.ic_notification_icon)
            .setContentTitle(localizedTitle)
            .setContentText(localizedBody)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)

        // 适配Android O及以上的通知渠道
        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                notificationChannelId,
                "本地化通知",
                NotificationManager.IMPORTANCE_DEFAULT
            )
            notificationManager.createNotificationChannel(channel)
        }

        // 显示通知
        notificationManager.notify(System.currentTimeMillis().toInt(), notificationBuilder.build())
    }
}

步骤3:添加本地化字符串

在res/values/strings.xml(默认语言)和res/values-es/strings.xml(西班牙语)等文件中添加对应翻译:

<!-- values/strings.xml -->
<string name="notification_welcome">Welcome!</string>
<string name="notification_content">You have a new message.</string>

<!-- values-es/strings.xml -->
<string name="notification_welcome">¡Bienvenido!</string>
<string name="notification_content">Tienes un nuevo mensaje.</string>

3. iOS 端实现

iOS需要开启后台远程通知权限,通过MessagingDelegate和UNUserNotificationCenter处理Data消息:

步骤1:开启后台权限

在Xcode中,进入项目的Capabilities -> 开启Background Modes -> 勾选Remote notifications。

步骤2:实现消息处理逻辑(Swift示例)

import FirebaseMessaging
import UserNotifications

class AppDelegate: UIResponder, UIApplicationDelegate, MessagingDelegate, UNUserNotificationCenterDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 初始化Firebase
        FirebaseApp.configure()
        Messaging.messaging().delegate = self

        // 请求通知权限
        UNUserNotificationCenter.current().delegate = self
        let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { _, _ in }
        application.registerForRemoteNotifications()

        return true
    }

    // 处理前后台收到的Data消息
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        // 提取Data对象
        guard let data = userInfo["data"] as? [String: String] else {
            completionHandler(.failed)
            return
        }
        let titleKey = data["translatable_title_key"] ?? ""
        let bodyKey = data["translatable_body_key"] ?? ""

        // 获取本地化文本
        let localizedTitle = NSLocalizedString(titleKey, comment: "")
        let localizedBody = NSLocalizedString(bodyKey, comment: "")

        // 创建通知内容
        let content = UNMutableNotificationContent()
        content.title = localizedTitle
        content.body = localizedBody
        content.sound = UNNotificationSound.default

        // 创建通知请求
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)

        // 发送通知
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("通知发送失败:\(error.localizedDescription)")
                completionHandler(.failed)
            } else {
                completionHandler(.newData)
            }
        }
    }

    // 前台收到通知时的展示控制
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound, .badge])
    }
}

步骤3:添加本地化字符串

在项目中创建Localizable.strings文件,添加不同语言的翻译:

// Localizable.strings (English)
"notification_welcome" = "Welcome!";
"notification_content" = "You have a new message.";

// Localizable.strings (Spanish)
"notification_welcome" = "¡Bienvenido!";
"notification_content" = "Tienes un nuevo mensaje.";

关键注意事项

  • Android端:如果之前用的是混合Payload(同时有notification和data),后台状态下系统会优先显示notification内容,data只能在点击通知后获取,所以一定要改用纯Data Payload。
  • iOS端:content-available: 1是触发后台处理的关键,必须配置;另外,后台唤醒的处理时间有限(约30秒),避免执行耗时操作。
  • 本地化键要统一,确保Cloud Function发送的键和App端的字符串键完全匹配。

内容的提问来源于stack exchange,提问作者José

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:36:25