fix: Add background service #37

ref: #31
This commit is contained in:
Janez T
2026-04-26 08:24:09 +02:00
parent 0008eff1b8
commit 9b8b1bf473
2 changed files with 130 additions and 3 deletions

View File

@@ -1,4 +1,5 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<!-- Bluetooth permissions --> <!-- Bluetooth permissions -->
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" /> <uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
@@ -62,6 +63,12 @@
<meta-data <meta-data
android:name="flutterEmbedding" android:name="flutterEmbedding"
android:value="2" /> android:value="2" />
<service
android:name="id.flutter.flutter_background_service.BackgroundService"
android:exported="false"
android:foregroundServiceType="location"
android:stopWithTask="false"
tools:replace="android:exported" />
</application> </application>
<!-- Required to query activities that can process text, see: <!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and https://developer.android.com/training/package-visibility and

View File

@@ -1,5 +1,8 @@
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'dart:ui';
import 'package:flutter_background_service/flutter_background_service.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter/widgets.dart'; import 'package:flutter/widgets.dart';
import 'package:geolocator/geolocator.dart'; import 'package:geolocator/geolocator.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
@@ -14,8 +17,13 @@ class BackgroundLocationService {
static const String _prefKeyDistance = 'background_tracking_distance'; static const String _prefKeyDistance = 'background_tracking_distance';
static const String _prefKeyLastLat = 'background_last_lat'; static const String _prefKeyLastLat = 'background_last_lat';
static const String _prefKeyLastLon = 'background_last_lon'; static const String _prefKeyLastLon = 'background_last_lon';
static const String _notificationChannelId =
'meshcore_sar_background_tracking';
static const int _notificationId = 9101;
MeshCoreBleService? _bleService; MeshCoreBleService? _bleService;
final FlutterBackgroundService _service = FlutterBackgroundService();
bool _serviceConfigured = false;
String _scopedKey(String baseKey) { String _scopedKey(String baseKey) {
return ProfileStorageScope.scopedKey(baseKey); return ProfileStorageScope.scopedKey(baseKey);
@@ -33,8 +41,6 @@ class BackgroundLocationService {
/// Start location tracking and automatic advertisement /// Start location tracking and automatic advertisement
/// Returns true if successful, false otherwise /// Returns true if successful, false otherwise
/// ///
/// Note: This is foreground tracking. For true background operation,
/// additional platform-specific configuration is required.
Future<bool> startTracking({double distanceThreshold = 10.0}) async { Future<bool> startTracking({double distanceThreshold = 10.0}) async {
if (!_isInitialized || _bleService == null) { if (!_isInitialized || _bleService == null) {
debugPrint( debugPrint(
@@ -80,6 +86,8 @@ class BackgroundLocationService {
await prefs.setBool(_scopedKey(_prefKeyEnabled), true); await prefs.setBool(_scopedKey(_prefKeyEnabled), true);
await prefs.setDouble(_scopedKey(_prefKeyDistance), distanceThreshold); await prefs.setDouble(_scopedKey(_prefKeyDistance), distanceThreshold);
await _startForegroundService(distanceThreshold);
// Start listening to position updates // Start listening to position updates
Position? lastPosition; Position? lastPosition;
try { try {
@@ -171,12 +179,87 @@ class BackgroundLocationService {
debugPrint('🛑 [BackgroundLocation] Stopping tracking'); debugPrint('🛑 [BackgroundLocation] Stopping tracking');
await _positionSubscription?.cancel(); await _positionSubscription?.cancel();
_positionSubscription = null; _positionSubscription = null;
await _stopForegroundService();
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
await prefs.setBool(_scopedKey(_prefKeyEnabled), false); await prefs.setBool(_scopedKey(_prefKeyEnabled), false);
debugPrint('✅ [BackgroundLocation] Tracking stopped'); debugPrint('✅ [BackgroundLocation] Tracking stopped');
} }
Future<void> _startForegroundService(double distanceThreshold) async {
if (!Platform.isAndroid && !Platform.isIOS) {
return;
}
try {
if (!_serviceConfigured) {
await _configureForegroundService();
}
final running = await _service.isRunning();
if (!running) {
await _service.startService();
}
_service.invoke('trackingUpdate', {
'distanceThreshold': distanceThreshold,
});
} catch (e) {
debugPrint('⚠️ [BackgroundLocation] Foreground service start failed: $e');
}
}
Future<void> _stopForegroundService() async {
if (!Platform.isAndroid && !Platform.isIOS) {
return;
}
try {
if (await _service.isRunning()) {
_service.invoke('stopService');
}
} catch (e) {
debugPrint('⚠️ [BackgroundLocation] Foreground service stop failed: $e');
}
}
Future<void> _configureForegroundService() async {
const channel = AndroidNotificationChannel(
_notificationChannelId,
'Background tracking',
description:
'Keeps MeshCore SAR location sharing active while the app is in the background.',
importance: Importance.low,
);
final notifications = FlutterLocalNotificationsPlugin();
await notifications
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin
>()
?.createNotificationChannel(channel);
await _service.configure(
androidConfiguration: AndroidConfiguration(
onStart: meshCoreSarBackgroundServiceStart,
autoStart: false,
autoStartOnBoot: false,
isForegroundMode: true,
notificationChannelId: _notificationChannelId,
initialNotificationTitle: 'MeshCore SAR',
initialNotificationContent: 'Maintaining background tracking',
foregroundServiceNotificationId: _notificationId,
foregroundServiceTypes: [AndroidForegroundType.location],
),
iosConfiguration: IosConfiguration(
autoStart: false,
onForeground: meshCoreSarBackgroundServiceStart,
onBackground: meshCoreSarBackgroundServiceIos,
),
);
_serviceConfigured = true;
}
/// Update the distance threshold for location updates /// Update the distance threshold for location updates
/// Note: This will restart tracking with the new threshold /// Note: This will restart tracking with the new threshold
Future<void> updateDistanceThreshold(double distance) async { Future<void> updateDistanceThreshold(double distance) async {
@@ -212,3 +295,40 @@ class BackgroundLocationService {
); );
} }
} }
@pragma('vm:entry-point')
Future<bool> meshCoreSarBackgroundServiceIos(ServiceInstance service) async {
WidgetsFlutterBinding.ensureInitialized();
DartPluginRegistrant.ensureInitialized();
return true;
}
@pragma('vm:entry-point')
void meshCoreSarBackgroundServiceStart(ServiceInstance service) {
DartPluginRegistrant.ensureInitialized();
if (service is AndroidServiceInstance) {
service.setAsForegroundService();
service.setForegroundNotificationInfo(
title: 'MeshCore SAR',
content: 'Maintaining background tracking',
);
}
service.on('trackingUpdate').listen((event) {
if (service is AndroidServiceInstance) {
final threshold = event?['distanceThreshold'];
final suffix = threshold is num
? ' (${threshold.toStringAsFixed(0)} m updates)'
: '';
service.setForegroundNotificationInfo(
title: 'MeshCore SAR',
content: 'Maintaining background tracking$suffix',
);
}
});
service.on('stopService').listen((event) {
service.stopSelf();
});
}