Flutter - How to Send location updates to back-end in real-time, periodically, running in background. (on both android and IOS)

Viewed 1038

I want to send the user's location updates, periodically, to our back-end service, in real-time, in the background ( even if the App is not running / terminated ).

Currently we are sending location updates over a web-socket between the App and back-end.

The problem is that the web-socket disconnected when (App terminated, battery optimization, or App in background and OS needs more memory).

How to keep the web-socket connected (maybe 12 hours a day)?

Is using web-sockets, in this case, a bad practice?

What is a good alternative to send location updates in real-time? ( please keep in mind that the back-end uses the web-socket to send data to the app (but not frequently, we may use push notification instead). ).

I am using geolocator package to get the user's current location. And socket_io_client package to connect to the web-socket.

We are targeting both Android and IOS.

Current implementation

// imports ...

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(
        socket: Geolocator.getPositionStream(),
        positionStream:  IO.io(kHost, <String, dynamic>{ 'transports': ['websocket'] }),
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({this.socket, this.positionStream});

  final Stream<Position> positionStream;
  final IO.Socket socket;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  void listenToPosStream() {
    widget.positionStream.listen((Position position) {
      if (position != null)
        updatePosition(latitude: position.latitude, longitude: position.longitude);
    });
  }

  void updatePosition({@required latitude, @required longitude}) {
    widget.socket.emit(
        'setPosition',
        {'latitude': latitude, 'longitude': longitude},
    );
  }

  @override
  void initState() {

    listenToPosStream();

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // rest of code ...
  }
}
0 Answers
Related