无需Firebase,Flutter如何搭建后台服务实现APP关闭后接收通知?
实现Flutter应用关闭后接收通知(无Firebase方案)
针对你提到的需求,结合Android和iOS的后台机制差异,分享以下可行方案,全程无需依赖Firebase:
一、无Firebase的后台常驻服务实现
Android端
Android 8.0+对后台服务限制严格,普通后台服务在APP关闭后会被系统回收,必须通过前台服务才能维持常驻:
- 先在
AndroidManifest.xml中添加必要权限:<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/> <uses-permission android:name="android.permission.WAKE_LOCK"/> - 配置
flutter_background_service时开启前台模式,同时初始化前台通知(系统要求前台服务必须显示通知):await FlutterBackgroundService().configure( androidConfiguration: AndroidConfiguration( onStart: _backgroundTask, autoStart: true, isForegroundMode: true, // 关键:开启前台服务 notificationChannelId: 'background_notification_channel', initialNotificationTitle: '应用后台运行中', initialNotificationContent: '正在监听通知更新', notificationIcon: '@mipmap/ic_launcher', // 替换成你的应用图标 ), iosConfiguration: IosConfiguration( autoStart: true, onForeground: _backgroundTask, onBackground: _iosBackgroundHandler, ), ); - 在
_backgroundTask中实现轻量的通知拉取逻辑,比如定时调用你的后端API检查新通知,注意控制请求频率(比如5-15分钟一次),避免过度耗电。
iOS端
iOS的后台机制更苛刻,APP完全关闭后无法运行自定义后台服务,只能利用系统允许的后台能力:
- 开启
Background Fetch:在Xcode的项目Capabilities中打开Background Modes,勾选Background Fetch,然后用flutter_background_service或background_fetch插件实现定时拉取逻辑。不过这种模式下,系统会根据APP使用频率调度拉取时机,无法精确控制时间。 - 如果需要APP关闭后也能实时接收通知,只能通过苹果的APNs推送服务,自己搭建后端向APNs发送推送请求,系统会直接将通知展示在通知栏,无需APP运行。
二、关闭后接收通知的具体方案
Android(APP完全关闭后)
- 前台服务+定时拉取:通过上述前台服务常驻后台,定时拉取后端通知数据,一旦有新通知,用
flutter_local_notifications弹出系统通知。 - WorkManager周期性任务:使用
flutter_workmanager插件,设置周期性任务,即使APP被关闭,WorkManager也会由系统触发任务,拉取通知并展示。这种方式比前台服务更省电,适合非实时的通知场景。
iOS(APP完全关闭后)
只能依赖APNs推送:自己搭建后端服务,集成APNs推送逻辑,当有新通知时,后端向苹果APNs服务器发送推送请求,系统会直接将通知推送到用户设备的通知栏,无需APP处于运行状态。
三、现有插件的优化建议
- 针对
flutter_background_service:- Android端务必开启
isForegroundMode: true,否则APP关闭后服务会被系统快速回收。 - 后台任务中避免耗时操作,复杂逻辑建议用
Isolate处理,防止阻塞服务线程。
- Android端务必开启
- 针对
flutter_local_notifications:- Android端必须配置通知渠道(Android 8.0+要求),否则通知无法正常显示:
const AndroidNotificationChannel channel = AndroidNotificationChannel( 'notification_channel', // 渠道ID '通知渠道', // 渠道名称 description: '用于展示应用通知', // 渠道描述 importance: Importance.max, ); await flutterLocalNotificationsPlugin.resolvePlatformSpecificImplementation<AndroidFlutterLocalNotificationsPlugin>()?.createNotificationChannel(channel); - 实现
onSelectNotification回调,处理用户点击通知后的跳转逻辑。
- Android端必须配置通知渠道(Android 8.0+要求),否则通知无法正常显示:
内容的提问来源于stack exchange,提问作者Darmawan Z.
相关产品推荐
相关产品推荐

