Search code examples
androidgoogle-polyline

Android: Display received data from a foreground service onto a MapView inside an activity


I've implemented a foreground service for giving me the current location every 10 seconds. With the collected data I want to display a route on the map.

However, when dealing with location tracking and services, the screen of the phone won't be always on, because of battery saving. So the activity will call onPause(), onStop() methods and the earliest point for the MapView update will be after onResume(). Up to this moment on every broadcast to the activity I send the list of all LatLng objects, clear the route up to this moment and display again the route using a Polyline

It does the job, but somehow I find it very inefficient, speaking of system resources.

Alternative will be on every broadcast to save the received LatLng objects in a list like List<LatLng> points=new ArrayList<LatLng>(); initialized in the activity, and for displaying the data, computethe difference between the received coordinates and those who are already saved in the Activity's List, and display only those to the Polyline.

What do you think? Is there also a better approach than these two?


Solution

  • Firstly, i have to mention stackoverflow is about a question regarding code optimizations, bugs, software problems and solutions not ideas.

    A foreground service every 10 seconds will be expensive regarding CPU and battery. With that being said, there are a few ways you can go around this:

    // Store data in somekind of database
    1- SQLite (On the phone not recommended as writing and reading database values can take alot of time and be resource-extensive)
    2- Firebase(Remote best option)
    3- SharedPrefernces(On the phone but single key-value pairs works for your case )
    

    Firebase tutorial : https://www.androidauthority.com/create-a-gps-tracking-application-with-firebase-realtime-databse-844343/

    //To minimize resource usages instead of a foreground service consider but try to increase your time between requests.
    1-AlarmManger
    2-setWindow
    3-setExact
    

    Finally, please do not remove your old polyline and create a new one as graphics are memory and battery enemy. just do something like:

    LatLng somePoint = new LatLng(location.getLatitude(), location.getLongitude());
    
    //Then add this point to the existing `polyline`:
    
    List<LatLng> fullPointList = somePolyLine.getPoints();
    fullPointList.add(somePoint);
    somePolyLine.setPoints(fullPointList);