diff --git a/lib/services/background_service.dart b/lib/services/background_service.dart index c8a83656..ccc084c3 100644 --- a/lib/services/background_service.dart +++ b/lib/services/background_service.dart @@ -6,6 +6,27 @@ import '../l10n/locale_tag.dart'; import '../utils/platform_info.dart'; class BackgroundService { + /// Options for the service that keeps the radio link alive in the + /// background. + /// + /// The radio link lives in the app process; once the user swipes the app + /// away it is gone, so a lingering "connected" notification (or an + /// automatic restart) would only be misleading. Swiping away stops the + /// service through `android:stopWithTask="true"` in AndroidManifest.xml. + /// + /// `stopWithTask` must stay unset here: in flutter_foreground_task (9.2 to + /// 11.0 at least) the option does not watch the task but stops the service + /// as soon as no activity is resumed, which is every time the app goes to + /// the background or the screen turns off. Android then caches and freezes + /// the process, the Bluetooth link drops and the low-memory killer ends it. + @visibleForTesting + static final ForegroundTaskOptions taskOptions = ForegroundTaskOptions( + eventAction: ForegroundTaskEventAction.repeat(5000), + autoRunOnBoot: false, + allowWifiLock: false, + allowAutoRestart: false, + ); + bool _initialized = false; String? Function()? _languageOverrideProvider; @@ -30,16 +51,7 @@ class BackgroundService { showNotification: false, playSound: false, ), - foregroundTaskOptions: ForegroundTaskOptions( - eventAction: ForegroundTaskEventAction.repeat(5000), - autoRunOnBoot: false, - allowWifiLock: false, - // The radio link lives in the app process; once the user swipes the - // app away it is gone, so a lingering "connected" notification (or - // an automatic restart) would only be misleading. - allowAutoRestart: false, - stopWithTask: true, - ), + foregroundTaskOptions: taskOptions, ); _initialized = true; } diff --git a/test/services/background_service_test.dart b/test/services/background_service_test.dart new file mode 100644 index 00000000..06912993 --- /dev/null +++ b/test/services/background_service_test.dart @@ -0,0 +1,15 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/services/background_service.dart'; + +void main() { + test('the foreground service does not stop when the app goes to the ' + 'background', () { + // flutter_foreground_task's stopWithTask option stops the service on the + // first activity pause, not on task removal. Swipe-away is handled by + // android:stopWithTask in the manifest instead. + final options = BackgroundService.taskOptions; + expect(options.stopWithTask, isNull); + expect(options.toJson().containsKey('stopWithTask'), isFalse); + expect(options.allowAutoRestart, isFalse); + }); +}