How do I send data to Firestore when app is killed?

  1. Summary of my problem

I have been working on a project where I need to get the location data of a user and send it to Firestore in the background(ie, when the app is killed)

Is this possible to do? If yes how? If not how do I try to implement something similar?

I am using flutter to build the app.

Thanks

Hello, from what I understand in https://flutter.dev/docs/get-started/flutter-for/android-devs#how-do-i-listen-to-android-activity-lifecycle-events, the observable lifecycle events are:

  • inactive — The application is in an inactive state and is not receiving user input. This event only works on iOS, as there is no equivalent event to map to on Android.
  • paused — The application is not currently visible to the user, not responding to user input, and running in the background. This is equivalent to onPause() in Android.
  • resumed — The application is visible and responding to user input. This is equivalent to onPostResume() in Android.
  • suspending — The application is suspended momentarily. This is equivalent to onStop in Android; it is not triggered on iOS as there is no equivalent event to map to on iOS.

I’m not sure, the killing of the app is an event you can observe.
Anyway, maybe your interested in this S.O. discussion (from which I got the above link), containing an example code snippet too.

See also https://github.com/flutter/flutter/issues/19594, where it is reported that:

suspending is the closed and to my experience it is also called before the app is killed.

hth

Thanks for your response! The above link shares info on how to access the current state of the user. Is there a way I can send data to Firestore Database when the app is in ‘paused’ state?

Hi, I haven’t done anything alike yet, but following that post example I would try something like

WidgetsBinding.instance.addObserver(LifecycleEventHandler(
    pausedCallBack: () async {
      // send data to Firestore
    }));

and in the LifecycleEventHandler class

class LifecycleEventHandler extends WidgetsBindingObserver {
  LifecycleEventHandler({this.pausedCallBack});

  final FutureVoidCallback pausedCallBack;

  @override
  Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
    switch (state) {
      case AppLifecycleState.inactive:
      case AppLifecycleState.paused:
        await pausedCallBack();
        break;
      case AppLifecycleState.detached:
      case AppLifecycleState.resumed:
    }
}

Please notice that this is just speculation, but If I had to solve that requirement, I’d give it a try. Hth

Thank you so much! I will try this out and let you know if it worked