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

无需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完全关闭后)

  1. 前台服务+定时拉取:通过上述前台服务常驻后台,定时拉取后端通知数据,一旦有新通知,用flutter_local_notifications弹出系统通知。
  2. WorkManager周期性任务:使用flutter_workmanager插件,设置周期性任务,即使APP被关闭,WorkManager也会由系统触发任务,拉取通知并展示。这种方式比前台服务更省电,适合非实时的通知场景。

iOS(APP完全关闭后)

只能依赖APNs推送:自己搭建后端服务,集成APNs推送逻辑,当有新通知时,后端向苹果APNs服务器发送推送请求,系统会直接将通知推送到用户设备的通知栏,无需APP处于运行状态。

三、现有插件的优化建议

  • 针对flutter_background_service:
    • Android端务必开启isForegroundMode: true,否则APP关闭后服务会被系统快速回收。
    • 后台任务中避免耗时操作,复杂逻辑建议用Isolate处理,防止阻塞服务线程。
  • 针对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回调,处理用户点击通知后的跳转逻辑。

内容的提问来源于stack exchange,提问作者Darmawan Z.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 03:43:22