0

NOTE This problem is only on android

  1. I implemented location service in the background to get location updates when the app is in the background (I do not need location when app is terminated, only need it when app is in the background) >>code: location.enableBackgroundMode(enable: true);

  2. I implemented listener to update realtime database (presence) when user starts/terminates the application. FirebaseDatabase.instance.reference().child('presence').child(id).onDisconnect().update({"status":"offline"};

When I terminate the app, "onDisconnect" DOES NOT fire (on android only), even after a longtime. When I remove the background location functionality, everything works perfectly.

My initial suspicion is that when the background location service is running, the VM is still connected for flutter and hence keeps the "app running", hence preventing the "onDisconnect" from firing.

When I keep both services (background location and onDisconnect) in the app and directly terminate the app from android studio (using "Q" on the Terminal), the VM terminates the app and everything works perfectly. Unfortunately, the app users will not have this option.

My Ask: Any suggestion that will help keep both functionality (background location and onDisconnect) and have onDisconnect fire (ONLY AN ANDROID ISSUE).

Thank you.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
theSpuka
  • 131
  • 1
  • 2

1 Answers1

0

You could capture the AppLifecycleState changes instead of relying on the onDisconnect of firebase realtime databases. This works on both iOS and Android and is more accurate.

Add the WidgetsBindingObserver to your stateful widget and the listeners as well.

Check for state == AppLifecycleState.paused to know it is running in the background.

class _HomeControlState extends State<HomeControl> with WidgetsBindingObserver {
    
    @override
    void didChangeAppLifecycleState(AppLifecycleState state) {
      // check here for the state of your app
    }

    @override
    void initState() {
      super.initState();
      WidgetsBinding.instance!.addObserver(this);
    }

    @override
    void dispose() 
      WidgetsBinding.instance!.removeObserver(this);
      super.dispose();
    }
}
Jelle
  • 1