import 'dart:async'; import 'package:background_location/background_location.dart'; import 'package:get/get.dart'; import 'package:permission_handler/permission_handler.dart'; class LocationBackgroundController extends GetxController { @override void onInit() { super.onInit(); requestLocationPermission(); configureBackgroundLocation(); } Future requestLocationPermission() async { var status = await Permission.locationAlways.status; if (!status.isGranted) { await Permission.locationAlways.request(); } } Future configureBackgroundLocation() async { await BackgroundLocation.setAndroidNotification( title: "Background Location", message: "Tracking location...", icon: "@mipmap/ic_launcher", ); BackgroundLocation.setAndroidConfiguration(1000); BackgroundLocation.startLocationService(); BackgroundLocation.getLocationUpdates((location) { // Handle location updates here print("New location: ${location.latitude}, ${location.longitude}"); }); } startBackLocation() async { Timer.periodic(const Duration(seconds: 5), (timer) { getBackgroundLocation(); }); } getBackgroundLocation() async { var status = await Permission.locationAlways.status; if (status.isGranted) { await BackgroundLocation.startLocationService( distanceFilter: 20, forceAndroidLocationManager: true); BackgroundLocation.setAndroidConfiguration( Duration.microsecondsPerSecond); // Set interval to 5 seconds BackgroundLocation.getLocationUpdates((location1) { print('''\n Latitude: ${location1.latitude.toString()} Longitude: ${location1.longitude.toString()} Altitude: ${location1.altitude.toString()} Accuracy: ${location1.accuracy.toString()} Bearing: ${location1.bearing.toString()} Speed: ${location1.speed.toString()} '''); }); } else { await Permission.locationAlways.request(); print('Location permission not granted'); } } }