firebase-messaging
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseFirebase Cloud Messaging Skill
Firebase Cloud Messaging 集成指南
This skill defines how to correctly use Firebase Cloud Messaging (FCM) in Flutter applications.
本指南介绍了如何在Flutter应用中正确使用Firebase Cloud Messaging (FCM)。
When to Use
适用场景
Use this skill when:
- Setting up push notifications with FCM in a Flutter project.
- Handling messages in foreground, background, and terminated states.
- Managing notification permissions and FCM tokens.
- Configuring platform-specific notification display behavior.
在以下场景中使用本指南:
- 在Flutter项目中使用FCM设置推送通知时。
- 处理前台、后台和终止状态下的消息时。
- 管理通知权限和FCM令牌时。
- 配置平台特定的通知显示行为时。
1. Setup and Configuration
1. 安装与配置
flutter pub add firebase_messagingiOS:
- Enable Push Notifications and Background Modes in Xcode.
- Upload your APNs authentication key to Firebase before using FCM.
- Do not disable method swizzling — it is required for FCM token handling.
- Ensure the bundle ID for your APNs certificate matches your app's bundle ID.
Android:
- Devices must run Android 4.4+ with Google Play services installed.
- Check for Google Play services compatibility in both and
onCreate().onResume()
Web:
- Create and register a service worker file named in your
firebase-messaging-sw.jsdirectory:web/
js
importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-messaging-compat.js");
firebase.initializeApp({ /* your config */ });
const messaging = firebase.messaging();
messaging.onBackgroundMessage((message) => {
console.log("onBackgroundMessage", message);
});flutter pub add firebase_messagingiOS:
- 在Xcode中启用推送通知和后台模式。
- 在使用FCM之前,将你的APNs认证密钥上传到Firebase。
- 请勿禁用方法混写(method swizzling)——这是FCM令牌处理所必需的。
- 确保APNs证书的Bundle ID与应用的Bundle ID匹配。
Android:
- 设备必须运行**Android 4.4+**并安装Google Play服务。
- 在和
onCreate()中检查Google Play服务的兼容性。onResume()
Web:
- 在目录中创建并注册一个名为
web/的服务工作者文件:firebase-messaging-sw.js
js
importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-app-compat.js");
importScripts("https://www.gstatic.com/firebasejs/10.7.0/firebase-messaging-compat.js");
firebase.initializeApp({ /* your config */ });
const messaging = firebase.messaging();
messaging.onBackgroundMessage((message) => {
console.log("onBackgroundMessage", message);
});2. Message Handling
2. 消息处理
Foreground messages:
dart
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Foreground message data: ${message.data}');
if (message.notification != null) {
print('Notification: ${message.notification}');
}
});Background messages:
dart
('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// Initialize Firebase before using other Firebase services in background
await Firebase.initializeApp();
print("Background message: ${message.messageId}");
}
void main() {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}Background handler rules:
- Must be a top-level function (not anonymous, not a class method).
- Annotate with (Flutter 3.3.0+) to prevent removal during tree shaking in release mode.
@pragma('vm:entry-point') - Cannot update app state or execute UI-impacting logic — runs in a separate isolate.
- Call before using any other Firebase services.
Firebase.initializeApp()
前台消息:
dart
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
print('Foreground message data: ${message.data}');
if (message.notification != null) {
print('Notification: ${message.notification}');
}
});后台消息:
dart
('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
// Initialize Firebase before using other Firebase services in background
await Firebase.initializeApp();
print("Background message: ${message.messageId}");
}
void main() {
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(MyApp());
}后台处理函数规则:
- 必须是顶级函数(不能是匿名函数或类方法)。
- 使用注解(Flutter 3.3.0+),防止在发布模式下被摇树优化移除。
@pragma('vm:entry-point') - 不能更新应用状态或执行影响UI的逻辑——它运行在单独的隔离区(isolate)中。
- 在使用任何其他Firebase服务之前,调用。
Firebase.initializeApp()
3. Permissions
3. 权限管理
dart
NotificationSettings settings = await FirebaseMessaging.instance.requestPermission(
alert: true,
badge: true,
sound: true,
announcement: false,
carPlay: false,
criticalAlert: false,
provisional: false,
);
print('Authorization status: ${settings.authorizationStatus}');- iOS / macOS / Web / Android 13+: Must request permission before receiving FCM payloads.
- Android < 13: returns
authorizationStatusif the user has not disabled notifications in OS settings.authorized - Android 13+: Track permission requests in your app — there's no way to determine if the user chose to grant/deny.
- Use provisional permissions on iOS () to let users choose notification types after receiving their first notification.
provisional: true
dart
NotificationSettings settings = await FirebaseMessaging.instance.requestPermission(
alert: true,
badge: true,
sound: true,
announcement: false,
carPlay: false,
criticalAlert: false,
provisional: false,
);
print('Authorization status: ${settings.authorizationStatus}');- iOS / macOS / Web / Android 13+:在接收FCM负载之前必须请求权限。
- Android < 13:如果用户未在系统设置中禁用通知,将返回
authorizationStatus。authorized - Android 13+:在应用中跟踪权限请求——无法判断用户是否选择授予/拒绝权限。
- 在iOS上使用临时权限(),让用户在收到第一条通知后选择通知类型。
provisional: true
4. Token Management
4. 令牌管理
Get FCM registration token (use to send messages to a specific device):
dart
final fcmToken = await FirebaseMessaging.instance.getToken();Web — provide VAPID key:
dart
final fcmToken = await FirebaseMessaging.instance.getToken(
vapidKey: "BKagOny0KF_2pCJQ3m....moL0ewzQ8rZu"
);Listen for token refresh:
dart
FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) {
// Send updated token to your application server
}).onError((err) {
// Handle error
});Apple platforms — ensure APNS token is available before FCM calls:
dart
final apnsToken = await FirebaseMessaging.instance.getAPNSToken();
if (apnsToken != null) {
// Safe to make FCM plugin API requests
}获取FCM注册令牌(用于向特定设备发送消息):
dart
final fcmToken = await FirebaseMessaging.instance.getToken();Web端 — 提供VAPID密钥:
dart
final fcmToken = await FirebaseMessaging.instance.getToken(
vapidKey: "BKagOny0KF_2pCJQ3m....moL0ewzQ8rZu"
);监听令牌刷新:
dart
FirebaseMessaging.instance.onTokenRefresh.listen((fcmToken) {
// Send updated token to your application server
}).onError((err) {
// Handle error
});苹果平台 — 确保在调用FCM前APNs令牌已可用:
dart
final apnsToken = await FirebaseMessaging.instance.getAPNSToken();
if (apnsToken != null) {
// Safe to make FCM plugin API requests
}5. Platform-Specific Behavior
5. 平台特定行为
- iOS: If the user swipes away the app from the app switcher, it must be manually reopened for background messages to work again.
- Android: If the user force-quits from device settings, the app must be manually reopened.
- Android foreground notifications: Create a "High Priority" notification channel to display notifications while the app is in the foreground.
- iOS foreground notifications: Update presentation options to display notifications while the app is in the foreground.
- iOS:如果用户从应用切换器中划走应用,必须手动重新打开才能让后台消息恢复工作。
- Android:如果用户从设备设置中强制退出应用,必须手动重新打开。
- Android前台通知:创建一个**“高优先级”**通知渠道,以便在应用前台时显示通知。
- iOS前台通知:更新展示选项,以便在应用前台时显示通知。
6. Auto-Initialization Control
6. 自动初始化控制
Disable auto-init — iOS ():
Info.plistFirebaseMessagingAutoInitEnabled = NODisable auto-init — Android ():
AndroidManifest.xmlxml
<meta-data android:name="firebase_messaging_auto_init_enabled" android:value="false" />
<meta-data android:name="firebase_analytics_collection_enabled" android:value="false" />Re-enable at runtime:
dart
await FirebaseMessaging.instance.setAutoInitEnabled(true);- The auto-init setting persists across app restarts once set.
禁用自动初始化 — iOS():
Info.plistFirebaseMessagingAutoInitEnabled = NO禁用自动初始化 — Android():
AndroidManifest.xmlxml
<meta-data android:name="firebase_messaging_auto_init_enabled" android:value="false" />
<meta-data android:name="firebase_analytics_collection_enabled" android:value="false" />在运行时重新启用:
dart
await FirebaseMessaging.instance.setAutoInitEnabled(true);- 自动初始化设置一旦设置,会在应用重启后保持生效。
7. iOS Image Notifications
7. iOS图片通知
Important: The iOS simulator does not display images in push notifications. Test on a physical device.
- Add a Notification Service Extension in Xcode.
- Use in the extension for image handling.
Messaging.serviceExtension().populateNotificationContent() - Swift: add the Swift package to your extension target.
FirebaseMessaging - Objective-C: add the pod to your Podfile.
Firebase/Messaging
重要提示: iOS模拟器不支持在推送通知中显示图片。请在物理设备上测试。
- 在Xcode中添加Notification Service Extension。
- 在扩展中使用处理图片。
Messaging.serviceExtension().populateNotificationContent() - Swift:将Swift包添加到你的扩展目标。
FirebaseMessaging - Objective-C:在Podfile中添加pod。
Firebase/Messaging