title: Flutter - How to Send location updates to back-end in real-time, periodically, running in background. (on both android and IOS)
body: <p>I want to send the user's location updates, periodically, to our back-end service, in real-time, in the background ( <strong>even if the App is not running / terminated</strong> ).</p>
  <p>Currently we are sending location updates over a web-socket between the App and back-end.</p>
  <p>The problem is that the web-socket disconnected when (App terminated, battery optimization, or App in background and OS needs more memory).</p>
  <p>How to keep the web-socket connected (maybe 12 hours a day)?</p>
  <p>Is using web-sockets, in this case, a bad practice?</p>
  <p>What is a good alternative to send location updates in real-time? ( <em>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).</em> ).</p>
  <p>I am using <a href="https://pub.dev/packages/geolocator" rel="nofollow noreferrer"><code>geolocator</code></a> package to get the user's current location. And <a href="https://pub.dev/packages/socket_io_client" rel="nofollow noreferrer"><code>socket_io_client</code></a> package to connect to the web-socket.</p>
  <p>We are targeting both <strong>Android and IOS</strong>.</p>
  <p>Current implementation</p>
  <pre class="lang-dart prettyprint-override"><code>// 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, &lt;String, dynamic&gt;{ 'transports': ['websocket'] }),
        ),
      );
    }
  }
  
  class MyHomePage extends StatefulWidget {
    MyHomePage({this.socket, this.positionStream});
  
    final Stream&lt;Position&gt; positionStream;
    final IO.Socket socket;
  
    @override
    _MyHomePageState createState() =&gt; _MyHomePageState();
  }
  
  class _MyHomePageState extends State&lt;MyHomePage&gt; {
  
    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 ...
    }
  }
  </code></pre>