能否使用FCM向其他用户推送通知?照片APP点赞场景下FCM的适用性与实现方案问询
当然靠谱!FCM(Firebase Cloud Messaging)绝对是这个场景的完美选择——不管用户B的App是在前台刷内容、后台挂着,甚至已经被完全关掉,都能稳稳把点赞通知推送到他的设备上。下面我就结合Flutter环境,给你一步步捋清楚怎么实现:
一、为什么FCM适配你的需求?
FCM天生就是为跨平台定向推送设计的:
- 支持后台/终止状态的通知送达,这正是你需要的核心能力
- 可以针对单个用户的设备令牌推送,精准定位到用户B
- 集成成本低,Flutter生态有完善的官方插件支持
二、具体实现步骤(Flutter + FCM)
1. 先搞定基础配置
- 去Firebase控制台创建项目,给你的Flutter App分别配置Android和iOS平台:下载
google-services.json(Android)和GoogleService-Info.plist(iOS),放到项目对应目录 - 在
pubspec.yaml里添加依赖:
然后执行dependencies: firebase_core: ^latest_version firebase_messaging: ^latest_version flutter_local_notifications: ^latest_version # 用来处理前台通知弹出flutter pub get安装依赖
2. 获取并绑定用户的FCM令牌
每个设备对应唯一的FCM令牌,你需要把这个令牌和用户B的账号绑定,存在你的后端数据库里,这样后端才能精准推送给用户B:
import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; Future<void> initFCM() async { // 初始化Firebase await Firebase.initializeApp(); // 获取当前设备的FCM令牌 String? fcmToken = await FirebaseMessaging.instance.getToken(); // 把令牌发送到你的后端,关联用户B的ID if (fcmToken != null) { // 调用你的后端API,比如: // await http.post(Uri.parse('https://your-api.com/save-token'), // body: {'userId': 'userB_unique_id', 'token': fcmToken}); } // 监听令牌刷新(令牌可能会不定期变化) FirebaseMessaging.instance.onTokenRefresh.listen((newToken) { // 调用后端API更新用户的令牌 }); }
3. 配置全状态的通知接收逻辑
前台状态接收通知
如果App在前台运行,FCM默认不会弹出系统通知,你需要用flutter_local_notifications手动弹出:
import 'package:flutter_local_notifications/flutter_local_notifications.dart'; final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin(); // 初始化本地通知插件 Future<void> initLocalNotifications() async { const AndroidInitializationSettings initializationSettingsAndroid = AndroidInitializationSettings('@mipmap/ic_launcher'); const InitializationSettings initializationSettings = InitializationSettings(android: initializationSettingsAndroid); await flutterLocalNotificationsPlugin.initialize(initializationSettings); } // 监听前台通知 void listenForegroundNotifications() { FirebaseMessaging.onMessage.listen((RemoteMessage message) { RemoteNotification? notification = message.notification; AndroidNotification? android = message.notification?.android; if (notification != null && android != null) { flutterLocalNotificationsPlugin.show( notification.hashCode, notification.title, notification.body, NotificationDetails( android: AndroidNotificationDetails( 'like_notification_channel', // 通知渠道ID '点赞通知', // 通知渠道名称 channelDescription: '接收他人点赞的通知', importance: Importance.max, priority: Priority.high, icon: android.smallIcon, ), ), ); } }); }
后台/终止状态接收通知
Android端:确保
AndroidManifest.xml里配置了FCM服务(添加依赖后通常会自动生成,若没有可以手动添加):<service android:name=".MyFirebaseMessagingService" android:exported="false"> <intent-filter> <action android:name="com.google.firebase.MESSAGING_EVENT"/> </intent-filter> </service>其中
MyFirebaseMessagingService需要继承FirebaseMessagingService,可以重写onMessageReceived处理后台消息(可选)。iOS端:在Xcode中开启推送通知权限,并且在
Info.plist里添加:<key>UIBackgroundModes</key> <array> <string>remote-notification</string> </array>处理通知点击逻辑:不管App处于什么状态,用户点击通知后都可以跳转到对应内容页面:
// 处理App终止状态下点击通知 FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) { if (message != null) { // 跳转到对应的点赞内容页面,比如: // Navigator.pushNamed(context, '/post-detail', arguments: message.data['postId']); } }); // 处理后台状态下点击通知 FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) { Navigator.pushNamed(context, '/post-detail', arguments: message.data['postId']); });
4. 后端触发点赞推送
当用户A完成点赞操作后,你的后端需要调用FCM的API,根据用户B的令牌发送通知:
示例HTTP请求(用服务器密钥鉴权):
POST https://fcm.googleapis.com/fcm/send Content-Type: application/json Authorization: key=YOUR_FCM_SERVER_KEY { "to": "USER_B_FCM_TOKEN", // 从你的数据库取出用户B的令牌 "notification": { "title": "嘿,你收到了一个点赞", "body": "用户A给你的内容点了赞" }, "data": { "postId": "your_post_id", // 可选,用来跳转对应内容 "type": "like" } }
注意:YOUR_FCM_SERVER_KEY可以在Firebase控制台的“云消息传递”设置里找到,一定要保密,不能暴露在前端代码中。
三、几个关键注意事项
- 权限申请:iOS必须请求用户的推送权限,Android 13及以上需要申请
POST_NOTIFICATIONS权限,记得在App启动时处理权限请求 - Android通知渠道:Android 8.0及以上必须创建通知渠道,否则通知不会显示,上面的代码已经通过
flutter_local_notifications处理了这一点 - 测试验证:可以用Firebase控制台的“云消息传递”功能测试发送通知,分别验证前台、后台、终止状态下的接收情况
内容的提问来源于stack exchange,提问作者Naveen
相关产品推荐
相关产品推荐

