Files
meshcore-open/lib/services/background_service.dart
T
Juraj Bednar 7bb9def628 Keep the background service running when the app leaves the screen
flutter_foreground_task's stopWithTask option (9.2 to 11.0) does not wait
for the task to be removed: it registers activity lifecycle callbacks and
stops the service on the first onActivityPaused with no resumed activity.
So the "MeshCore background" service stopped every time the app went to
the background or the screen turned off. Android then cached and froze the
process, the Bluetooth link dropped and the low-memory killer ended the
app a few hours later. Usage stats on a Pixel show FOREGROUND_SERVICE_STOP
in the same second as every ACTIVITY_STOPPED.

Drop the option. android:stopWithTask="true" in the manifest still stops
the service when the app is swiped away, which is what the option was
meant to do.
2026-11-18 14:31:35 +01:00

130 lines
4.4 KiB
Dart

import 'package:flutter/widgets.dart';
import 'package:flutter_foreground_task/flutter_foreground_task.dart';
import '../l10n/app_localizations.dart';
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;
/// Allows the app to expose its current language override (e.g. from
/// AppSettingsService) so the foreground notification matches the app UI
/// language instead of only the system locale.
void setLanguageOverrideProvider(String? Function()? provider) {
_languageOverrideProvider = provider;
}
Future<void> initialize() async {
if (!PlatformInfo.isAndroid || _initialized) return;
FlutterForegroundTask.init(
androidNotificationOptions: AndroidNotificationOptions(
channelId: 'meshcore_background',
channelName: 'MeshCore Background',
channelDescription: 'Keeps MeshCore running in the background.',
channelImportance: NotificationChannelImportance.LOW,
priority: NotificationPriority.LOW,
),
iosNotificationOptions: const IOSNotificationOptions(
showNotification: false,
playSound: false,
),
foregroundTaskOptions: taskOptions,
);
_initialized = true;
}
Future<void> start() async {
if (!PlatformInfo.isAndroid) return;
if (!_initialized) {
await initialize();
}
final running = await FlutterForegroundTask.isRunningService;
if (running) return;
final l10n = await _loadLocalizations();
await FlutterForegroundTask.startService(
notificationTitle: l10n.background_serviceTitle,
notificationText: l10n.background_serviceText,
notificationIcon: const NotificationIcon(
metaDataName: 'org.meshcore.open.NOTIFICATION_ICON',
),
callback: startCallback,
);
}
Future<AppLocalizations> _loadLocalizations() async {
final supported = AppLocalizations.supportedLocales;
final override = _languageOverrideProvider?.call();
if (override != null && override.isNotEmpty) {
final overrideLocale = localeFromTag(override);
final isSupported = supported.any(
(l) => l.languageCode == overrideLocale.languageCode,
);
if (isSupported) {
return AppLocalizations.delegate.load(overrideLocale);
}
}
final preferred = WidgetsBinding.instance.platformDispatcher.locales;
final match = basicLocaleListResolution(preferred, supported);
return AppLocalizations.delegate.load(match);
}
static Future<void> openBatteryOptimizationSettings() async {
if (!PlatformInfo.isAndroid) return;
await FlutterForegroundTask.openIgnoreBatteryOptimizationSettings();
}
Future<void> stop() async {
if (!PlatformInfo.isAndroid) return;
final running = await FlutterForegroundTask.isRunningService;
if (!running) return;
await FlutterForegroundTask.stopService();
}
}
@pragma('vm:entry-point')
void startCallback() {
FlutterForegroundTask.setTaskHandler(_MeshCoreTaskHandler());
}
class _MeshCoreTaskHandler extends TaskHandler {
@override
Future<void> onStart(DateTime timestamp, TaskStarter starter) async {}
@override
void onRepeatEvent(DateTime timestamp) {}
@override
Future<void> onDestroy(DateTime timestamp, bool isTimeout) async {}
@override
void onNotificationButtonPressed(String id) {}
@override
void onNotificationPressed() {
FlutterForegroundTask.launchApp('/');
}
}