如何在Flutter应用中设置金价银价触发的推送通知?
Flutter 金价/银价后台监听与推送通知实现方案
核心问题拆解
- 后台持续监听Socket价格流
- 实时价格与用户设定值的比对逻辑
- 后台状态下触发本地推送通知
具体实现步骤
1. 后台Socket监听处理
Flutter原生Socket在后台会被系统限制,必须通过前台服务保活:
- Android端:在
AndroidManifest.xml添加权限:
用<uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.WAKE_LOCK" />flutter_foreground_task创建前台服务,将Socket连接逻辑放在服务回调中,确保后台进程不被系统杀死。 - iOS端:开启
Background Modes中的Voice over IP或Remote notifications权限,用isolate处理Socket消息,避免阻塞UI线程,同时用connectivity_plus监听网络状态,异常时自动重连。
2. 价格比对逻辑
将用户设定的目标价格存在SharedPreferences或本地数据库(如hive)中,每次收到Socket推送的实时价格时执行比对:
void checkPriceTrigger(double realTimePrice, double targetPrice, String metalType) { // 根据需求设置触发条件:大于等于/小于等于/精准匹配 if (realTimePrice >= targetPrice) { _showNotification(metalType, realTimePrice, targetPrice); // 触发后移除该提醒,避免重复推送 _removeTargetPrice(metalType); } }
注意遍历所有用户设定的目标价,逐一完成比对逻辑。
3. 本地推送通知实现
使用flutter_local_notifications包,支持前后台触发通知:
- 初始化Android通知通道(8.0+必填):
final AndroidNotificationChannel channel = AndroidNotificationChannel( 'price_alerts', '金价银价提醒', description: '价格达到设定值时推送通知', importance: Importance.high, ); await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel); - 触发通知的核心方法:
Future<void> _showNotification(String metalType, double realPrice, double targetPrice) async { const AndroidNotificationDetails androidDetails = AndroidNotificationDetails( 'price_alerts', '金价银价提醒', channelDescription: '价格触发提醒', priority: Priority.high, importance: Importance.high, ); const NotificationDetails notificationDetails = NotificationDetails(android: androidDetails); await flutterLocalNotificationsPlugin.show( DateTime.now().millisecondsSinceEpoch % 10000, '$metalType价格触发提醒', '当前价格${realPrice.toStringAsFixed(2)},已达到您设定的${targetPrice.toStringAsFixed(2)}', notificationDetails, payload: 'price_alert', ); }
4. 避免重复推送的处理
- 触发通知后,将已触发的目标价从存储中移除
- 或给每个目标价添加
isTriggered标记,比对时跳过已触发项
关键注意事项
- Android端:前台服务会显示常驻通知,这是系统强制要求,可自定义通知样式提升友好度
- iOS端:后台Socket监听时长受系统限制,长时间后台可能被暂停,可补充服务器侧APNs推送(服务器检测到价格达标时,给用户发远程推送)
- 电量优化:给Socket添加心跳机制,减少频繁重连的电量消耗
内容的提问来源于stack exchange,提问作者RASAL
相关产品推荐
相关产品推荐

