Follow

Location updates and path tracking in Android

Introduction

In this era of rapidly changing technology, mobile devices have made their way into all spheres of an individual’s life. Their role in daily life has been increasing tremendously and they are being used for much more than the basic purpose of communication. Android has emerged into the mobile world with an intention to develop a mobile platform OS. It has a tremendous potential in developing smart phones which are aware of its owner’s location and preferences.

Knowing the user’s location is one of the most prominent feature that we have in Android. It can be used to track the path that user went through or to find the current location of a person to identify where he/she is.
Android has provided two API’s from which we can get the location of the device. In this blog, we are going to shed some light on the location API’s usage, working of location awareness in Android and how it will be useful in the real-time world.

The following are the main points which will be addressed in the later sections of the blog:

  • Why do we need to know user location?
  • What are the different ways to get a location in Android?
  • How do we get location data using available API’s?
  • Which one is the best among available location API’s?
  • What are the advantages and disadvantages of each location tracking API?

Why do we need to know user location? 

User location comes in handy when a user should be tracked continuously.
Eg: In an Uber app, tracking the current location of the cab is made possible using continuous location
tracking. In a fitness app, user’s path can be known by getting continuous location updates.

In a certain context, an app might need location updates periodically. Let’s say we are building a direction app and the user needs to get updated whenever the location is changed. In such case, we need to request for location updates.

Like above-mentioned examples, location can be used in many areas and is deemed a powerful information for computing results and to make things easy for the user.

What are the different ways to get a location in Android?

There are two conventional ways by which we can get location updates in Android. They are:

  1. Location manager
  2. Fused Location Provider

How do we get location data using available API’s?

1. Location Manager: 

Location Manager is an android framework class. It provides access to the system location services. It can get the location from GPS, NETWORK and WI-FI. But at a given time, it can get the location from only one provider.

State of platform API’s with Location manager:

LocationManager Platform States
Image Credit: Screenshot from Google I/O 2013

System permissions required by Location Manager are

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Here is the code snippet for Location Manager

// Initialize location services
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

// Start requesting for location
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime, minDistance, listener);

// When a location change update comes from system, this listener will handle it
private final LocationListener listener = new LocationListener() {

     @Override
     public void onStatusChanged(String provider, int status, Bundle extras) {
     }

     @Override
     public void onProviderEnabled(String provider) {
     }

     @Override
     public void onProviderDisabled(String provider) {
     }

     @Override
     public void onLocationChanged(Location location) {
        // Do basic filtering of received locations and save into the database for further processing.
     }
};

Location Tracker Path

2. Fused Location Provider (FLP): 

Fused Location Provider uses a mix of hardware i.e it gives the accurate location of the user computed by a system based on the available providers (GPS, Network and Wi-fi).

State of platform API’s with Fused location provider:

FLP States of Platform
Image Credit: Screenshot from Google I/O 2013

System permissions required by Fused Location Provider are

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Google Play Services is required for FLP to work. So, add the following dependencies to build.gradle file. Always use the stable and the latest version of play services.

dependencies { compile 'com.google.android.gms:play-services:9.0'}

Here is the code snippet for FLP.

// First we have to create google api client object, so that we can access the google api’s that we have.
mLocationClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(connectionCallback)
        .addOnConnectionFailedListener(connectionFailListener)
        .addApi(LocationServices.API).build();

//connectionCallback is to handle call back methods like onConnected and onConnectionSuspended
//connectionFailListener will handle call back method when connection to GoogleApiClient is failed.

// This is to set parameters for location and create location object
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(UPDATE_INTERVAL); 
//Here the UPDATE_INTERVAL(interval in milliseconds) is the interval rate at which we want to receive location updates

// Call back methods to handle call back events and act accordingly depending on the response that we get.
GoogleApiClient.OnConnectionFailedListener connectionFailListener = new 
GoogleApiClient.OnConnectionFailedListener() {
    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
         // When connection is failed, we can try to reconnect.  
    }
};

GoogleApiClient.ConnectionCallbacks connectionCallback = new GoogleApiClient.ConnectionCallbacks() {
    @Override
    public void onConnected(Bundle bundle) {
        // GooglePlayServices should be properly configured to receive location updates, 
        // we need to implement this method.If there are issues with GoolgePlayServices we need to intimate user.
        checkGooglePlayServiceSettings();
      
        // Check if location client is connected or not, if connected request for location updates
        if(mLocationClient.isConnected()) {
               LocationServices.FusedLocationApi.requestLocationUpdates(mLocationClient, 
               mLocationRequest, mLocationMonitor);
        }
    }

    @Override
    public void onConnectionSuspended(int reason) {
       // When a connection is suspended, we can try to reconnect or else pass the information to user.
    }
}; 

// LocationMonitor is a custom method which implement location listener
// When a location change update comes from system, this listener will handle it
private class LocationMonitor implements com.google.android.gms.location.LocationListener {
     @Override
     public void onLocationChanged(Location location) {
      // Do basic filtering of received locations and save into the database for further processing.                   
     }
}

To get location updates continuously, we need to execute the above code inside a service class. Doing so will help to get location updates even when the application is not running (It will work in prior to Android O).

Location Parameters:

Accuracy: PRIORITY_HIGH_ACCURACY priority should be used to get the maximum accuracy. Along with this, there are other priorities like PRIORITY_LOW_POWER and PRIORITY_BALANCED_POWER_ACCURACY.

Location update interval:  Tracking user location in a moving vehicle needs location updates at faster intervals. If the interval rate is set to ‘0’, location updates are provided by the system based on the best available interval.

For example, a user location tracking app always delivers best results even in a moving vehicle, if the update interval is set to ‘0’. The other case where update interval can be set to a value is when the user is walking or riding a bicycle. Because here we don’t need updates at faster rates. More the interval rate, less the frequency of location updates.

Fused location API accuracy statistics:

FLP_Accuracy levels
Image Credit: Screenshot from Google I/O 2013

Battery Optimization: 

During our journey with Location API’s, we found that the battery consumption is high intermittently even though we are not actually using the app.

After a lot of real time verifications, discussions and analysis, we came to the conclusion that, battery consumption is happening even when the location services are not running. This is because, even after shutting down the location service, “Location Client” disconnection is not releasing the GPS lock sporadically. Predominantly whenever “Location Client” is disconnected then the GPS lock will be released and it will not be used by app anymore.

To overcome this, we are disconnecting location client twice. This resulted in a better battery performance in most of the scenarios.

Which one is the best among available android location API’s?

Among the location API’s that are available in Android, Fused location provider is the efficient one in terms of accuracy and power consumption.

In location manager, it is required to mention the provider to use, for receiving location updates i.e GPS, NETWORK or WI-FI. In FLP, we get location based on the best among all the providers and therefore it is called ‘Fused location’.

Advantages and disadvantages

Fused Location Provider (FLP)

Advantages :

1. Fused Location Provider uses a mix of hardware to determine the location based on the context of the request.
2. Accuracy is good.
3. Power consumption is low.
4. Provides location even inside buildings.

Disadvantages :
       1. To use Location Services, Google play services should be installed.

Location Manager

Advantages :

1. Does not bank on the Google Play Services.

Disadvantages :

1. To get the precise location, we need to switch between network and GPS location providers
(as GPS doesn’t work indoors).
2. Switching between the location providers costs battery, which leads to battery drain.

Conclusion

The bottom line is, when choosing the location APIs, it all comes down to the accuracy. But the accuracy of the location also depends on the GPS chipset present in the mobile. So, the different mobile devices receive location points with varying accuracies.

We have faced an issue when we were working with Moto G3 mobile, with FLP giving speed always as ‘0’. We have used LocationManager services as speed is a vital information in our app. Erratically, we receive inaccurate (location points which have an accuracy in hundreds) data from both LocationManager and Fused Location Provider, so it is recommended to filter the received location data and process it for efficient output. This filtering includes discarding inaccurate data, reducing the location update frequency rate.
By all means, while choosing a location API to use in your application, consider all the above factors and make sure you pick the one which doesn’t affect the overall performance of the application and provides the best results.

Posted By: Reenath T, Osmosee

Are you interested? follow us and get notified of new posts

One thought on “Location updates and path tracking in Android

Leave A Reply