68 lines
2.0 KiB
Dart
68 lines
2.0 KiB
Dart
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<void> 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<void> 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<void> 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();
|
|
}
|
|
}
|
|
}
|