Manas Bam
Manas Bam

Reputation: 155

Is it possible to track User's Location when app is killed (Flutter)

I am trying to track user's location when app is killed and send that location(Latitude and Longitude) to a database(Firestore) in Flutter.

I am a newbie and so I have no idea how to do this. It would be appreciated if someone could help me on this one.

Thanks so much!!

Upvotes: 6

Views: 11031

Answers (1)

Omatt
Omatt

Reputation: 10519

It's possible to fetch the device's location data while the app is running in the background. You mentioned that you'd like to achieve this even when the app is killed - by "killed", if you mean here fetching location data after being forced stop in Android, then this isn't possible.

If you like to fetch user data while the app is running the background, you can use the geolocator plugin. Though doing so have privacy implications, and you'll need to request permission from the user. The permission request is built-in to the geolocator plugin.

LocationPermission permission;

permission = await Geolocator.checkPermission();

After this you can then listen to the Stream and update the code snippet with however you want to store the location data.

import 'package:geolocator/geolocator.dart';

final LocationSettings locationSettings = LocationSettings(accuracy: LocationAccuracy.best);

StreamSubscription<Position> positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen(
    (Position? position) {
    print(position == null ? 'Unknown' : '${position.latitude.toString()}, ${position.longitude.toString()}');
    // Store geolocation data
});

To run the tasks in the background even when the app isn't running in the foreground, you can use workmanager.

Create a Workmanager for running the task and initialize it on the Flutter project's main.dart.

void locationHandler() {
  Workmanager().executeTask((_) {
    print('background task running'); 
    
    // Fetch device location data
  });
}

void main() {
  Workmanager().initialize(
    locationHandler, // The top level function, aka callbackDispatcher
    isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
  );
  Workmanager().registerOneOffTask('yourTaskName', 'yourTaskNameDescription);
  runApp(MyApp());
}

Upvotes: 1

Related Questions