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

如何在用户杀死Flutter应用时停止flutter_background_service?

解决杀死Flutter应用时无法停止flutter_background_service的问题

这个问题需要针对Android和iOS平台的生命周期逻辑差异分别处理:

Android 端解决方案

当用户杀死应用时,系统会触发Service的onTaskRemoved方法,我们可以通过自定义Service重写该方法实现自动停止服务:

  1. 创建自定义Android Service类
    在android/app/src/main/kotlin/[你的包名]/路径下新建CustomBackgroundService.kt:
package com.your.package.name

import io.flutter.plugins.backgroundservice.FlutterBackgroundService

class CustomBackgroundService : FlutterBackgroundService() {
    override fun onTaskRemoved(rootIntent: android.content.Intent?) {
        super.onTaskRemoved(rootIntent)
        // 应用被杀死时自动停止服务
        stopSelf()
    }
}
  1. 更新Flutter端配置
    初始化AndroidConfiguration时指定自定义Service的全类名:
final _androidConfiguration = AndroidConfiguration(
   onStart: _onStart,
   autoStart: true,
   isForegroundMode: true,
   initialNotificationTitle: 'App is running',
   initialNotificationContent: '',
   // 替换为你自定义Service的完整类路径
   serviceClass: "com.your.package.name.CustomBackgroundService",
);

iOS 端解决方案

iOS中应用被用户杀死时,系统会调用applicationWillTerminate回调,我们可以在此处通知后台服务停止:

修改ios/Runner/AppDelegate.swift:

import UIKit
import Flutter
import flutter_background_service_ios

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    FlutterBackgroundServicePlugin.setPluginRegistrantCallback { registry in
      GeneratedPluginRegistrant.register(with: registry)
    }
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  override func applicationWillTerminate(_ application: UIApplication) {
    // 应用终止时触发停止服务指令
    let service = FlutterBackgroundServicePlugin.shared
    service.invoke("stopService")
  }
}

Flutter 层资源优化

为确保定时器等资源及时释放,在_onStart方法中添加定时器取消逻辑:

@pragma('vm:entry-point')
void _onStart(ServiceInstance service) async {
  DartPluginRegistrant.ensureInitialized();
  Timer? periodicTimer; // 声明定时器变量

  if (service is AndroidServiceInstance) {
    service.on(BackGroundServiceOperations.setAsForeground).listen((event) {
      service.setAsForegroundService();
    });

    service.on(BackGroundServiceOperations.setAsBackground).listen((event) {
      service.setAsBackgroundService();
    });
  }

  service.on(BackGroundServiceOperations.stopService).listen((event) {
    periodicTimer?.cancel(); // 停止定时器
    service.stopSelf();
  });

  periodicTimer = Timer.periodic(const Duration(seconds: 5), (timer) {
    debugPrint("background service is running!");
  });
}

完成以上配置后,无论Android还是iOS平台,用户杀死应用时后台服务都会自动停止,不会再出现持续打印日志的情况。

内容的提问来源于stack exchange,提问作者DeKekem

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 16:11:09