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(); } Future requestLocationPermission() async { var status = await Permission.locationAlways.status; if (!status.isGranted) { status = await Permission.locationAlways.request(); } if (status.isGranted) { configureBackgroundLocation(); } else { // Handle permission denial print("Location permission denied"); } } Future configureBackgroundLocation() async { await BackgroundLocation.setAndroidNotification( title: "Background Location", message: "Tracking location...", icon: "@mipmap/launcher_icon", ); // Set the location update interval to 5 seconds BackgroundLocation.setAndroidConfiguration(5000); BackgroundLocation.startLocationService(); BackgroundLocation.getLocationUpdates((location) { // Handle location updates here print("Latitude: ${location.latitude}, Longitude: ${location.longitude}"); }); startBackLocation(); } void startBackLocation() async { Timer.periodic(const Duration(seconds: 5), (timer) async { await getBackgroundLocation(); }); } Future getBackgroundLocation() async { var status = await Permission.locationAlways.status; if (status.isGranted) { // The location service is already started in configureBackgroundLocation // No need to call startLocationService again BackgroundLocation.getLocationUpdates((location) { // Handle location updates here print( "Latitude: ${location.latitude}, Longitude: ${location.longitude}"); }); } else { // Request permission if not granted await Permission.locationAlways.request(); } } }