Flutter Android前台服务启动失败致应用崩溃问题求助
使用flutter_background_service: ^5.0.5开发Flutter应用时,启动后几秒内就崩溃。已在AndroidManifest.xml中配置FOREGROUND_SERVICE和FOREGROUND_SERVICE_MEDIA_PROJECTION权限,但仍报错无法启动前台服务,同时出现ForegroundServiceDidNotStartInTimeException异常。
AndroidManifest.xml 配置
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION" />
关键错误提示(翻译后)
因SecurityException无法启动前台服务——是否忘记申请权限?——启动类型为mediaProjection的前台服务,调用应用ProcessRecord{b4e0284 12331:com.zioninvasion.prayer_buddy/u0a190},目标SDK版本34,需要满足以下权限要求:必须拥有所有权限(allOf=true)[android.permission.FOREGROUND_SERVICE_MEDIA_PROJECTION],且拥有任意一项权限(allOf=false)[android.permission.CAPTURE_VIDEO_OUTPUT, android:project_media]
完整崩溃日志(翻译后)
D/AndroidRuntime(12331): 正在关闭VM
E/AndroidRuntime(12331): FATAL EXCEPTION: main
E/AndroidRuntime(12331): 进程: com.zioninvasion.prayer_buddy, PID: 12331
E/AndroidRuntime(12331): android.app.RemoteServiceException$ForegroundServiceDidNotStartInTimeException: Context.startForegroundService() 未调用Service.startForeground():ServiceRecord{c93a6db u0 com.zioninvasion.prayer_buddy/id.flutter.flutter_background_service.BackgroundService}
E/AndroidRuntime(12331): at android.app.ActivityThread.generateForegroundServiceDidNotStartInTimeException(ActivityThread.java:2104)
E/AndroidRuntime(12331): at android.app.ActivityThread.throwRemoteServiceException(ActivityThread.java:2075)
E/AndroidRuntime(12331): at android.app.ActivityThread.-$$Nest$mthrowRemoteServiceException(Unknown Source:0)
E/AndroidRuntime(12331): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2369)
E/AndroidRuntime(12331): at android.os.Handler.dispatchMessage(Handler.java:106)
E/AndroidRuntime(12331): at android.os.Looper.loopOnce(Looper.java:205)
E/AndroidRuntime(12331): at android.os.Looper.loop(Looper.java:294)
E/AndroidRuntime(12331): at android.app.ActivityThread.main(ActivityThread.java:8177)
E/AndroidRuntime(12331): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(12331): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:552)
E/AndroidRuntime(12331): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:971)
E/AndroidRuntime(12331): Caused by: android.app.StackTrace: 最后一次调用startServiceCommon()是在此处
E/AndroidRuntime(12331): at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1952)
E/AndroidRuntime(12331): at android.app.ContextImpl.startForegroundService(ContextImpl.java:1906)
E/AndroidRuntime(12331): at android.content.ContextWrapper.startForegroundService(ContextWrapper.java:830)
E/AndroidRuntime(12331): at androidx.core.content.ContextCompat$Api26Impl.startForegroundService(ContextCompat.java:1189)
E/AndroidRuntime(12331): at androidx.core.content.ContextCompat.startForegroundService(ContextCompat.java:752)
E/AndroidRuntime(12331): at id.flutter.flutter_background_service.FlutterBackgroundServicePlugin.start(FlutterBackgroundServicePlugin.java:82)
E/AndroidRuntime(12331): at id.flutter.flutter_background_service.FlutterBackgroundServicePlugin.onMethodCall(FlutterBackgroundServicePlugin.java:121)
E/AndroidRuntime(12331): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:267)
E/AndroidRuntime(12331): at io.flutter.embedding.engine.dart.DartMessenger.invokeHandler(DartMessenger.java:295)
E/AndroidRuntime(12331): at io.flutter.embedding.engine.dart.DartMessenger.lambda$dispatchMessageToQueue$0$io-flutter-embedding-engine-dart-DartMessenger(DartMessenger.java:322)
E/AndroidRuntime(12331): at io.flutter.embedding.engine.dart.DartMessenger$$ExternalSyntheticLambda0.run(Unknown Source:12)
E/AndroidRuntime(12331): at android.os.Handler.handleCallback(Handler.java:958)
E/AndroidRuntime(12331): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(12331): ... 6 more
I/Process (12331): 发送信号. PID: 12331 SIG: 9
1. 补充权限配置与动态申请
错误提示明确要求:
- 必须持有
FOREGROUND_SERVICE_MEDIA_PROJECTION权限(已配置) - 还需持有
CAPTURE_VIDEO_OUTPUT或android:project_media中的任意一项
首先在AndroidManifest.xml添加缺失的权限(示例选CAPTURE_VIDEO_OUTPUT):
<uses-permission android:name="android.permission.CAPTURE_VIDEO_OUTPUT" />
针对Android 13+,需要动态申请权限,同时mediaProjection需通过系统弹窗获取用户授权,示例代码:
import 'package:flutter/material.dart'; import 'package:flutter_background_service/flutter_background_service.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:media_projection/media_projection.dart'; Future<void> requestPermissions() async { // 请求CAPTURE_VIDEO_OUTPUT权限 await Permission.captureVideoOutput.request(); // 请求MediaProjection授权,需在Activity中处理返回结果 final mediaProjectionManager = MediaProjectionManager(); final intent = await mediaProjectionManager.createScreenCaptureIntent(); // 启动Intent获取授权,后续将MediaProjection实例传递给后台服务 }
2. 给后台服务指定ForegroundServiceType
Target SDK 34要求必须在服务声明中指定android:foregroundServiceType="mediaProjection",修改AndroidManifest.xml中的服务配置:
<service android:name="id.flutter.flutter_background_service.BackgroundService" android:foregroundServiceType="mediaProjection" android:exported="false" />
3. 确保服务启动后立即调用startForeground()
ForegroundServiceDidNotStartInTimeException是因为调用startForegroundService()后10秒内未调用Service.startForeground()。检查服务初始化代码,确保启动后立刻配置前台通知:
Future<void> initializeService() async { final service = FlutterBackgroundService(); await service.configure( androidConfiguration: AndroidConfiguration( onStart: onStart, autoStart: true, isForegroundMode: true, notificationChannelId: "my_foreground_channel", initialNotificationTitle: "后台服务运行中", initialNotificationContent: "正在执行媒体投影任务", notificationIcon: "@mipmap/ic_launcher", ), iosConfiguration: IosConfiguration( autoStart: true, onForeground: onStart, onBackground: onIosBackground, ), ); } void onStart(ServiceInstance service) async { // 立即初始化前台通知,避免延迟 service.setForegroundNotificationInfo( title: "后台服务运行中", content: "正在执行媒体投影任务", ); // 后续业务逻辑 }
4. 检查插件版本兼容性
确认flutter_background_service: ^5.0.5是否完全支持Target SDK 34,若存在兼容问题,可尝试升级至最新版本,或查看插件官方issues排查同类问题。
内容的提问来源于stack exchange,提问作者Zionnite

