Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android : LocationManager vs Google Play Services

People also ask

What advantages do you get in using Google Play services API over the Android framework API for the location feature?

The Google Location Services API, part of Google Play Services, provides a more powerful, high-level framework that automatically handles location providers, user movement, and location accuracy. It also handles location update scheduling based on power consumption parameters you provide.

What is fused location app used for?

The fused location provider is a location API in Google Play services that intelligently combines different signals to provide the location information that your app needs.

What is fusedlocationproviderclient?

Requests location updates with the given request and results delivered to the given callback on the specified Executor . Task<Void> requestLocationUpdates(LocationRequest request, LocationCallback callback, Looper looper)


User Location on Android

Getting the user’s location on Android is a little less straightforward than on iOS. To start the confusion, there are two totally different ways you can do it. The first is using Android APIs from android.location.LocationListener, and the second is using Google Play Services APIs com.google.android.gms.location.LocationListener. Let’s go through both of them.

  1. Android’s Location API

    The Android’s location APIs use three different providers to get location -

    • LocationManager.GPS_PROVIDER — This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix.
    • LocationManager.NETWORK_PROVIDER — This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup.
    • LocationManager.PASSIVE_PROVIDER — This provider will return locations generated by other providers. You passively receive location updates when other applications or services request them without actually requesting the locations yourself.

The gist of it is that you get an object of LocationManager from the system, implement the LocationListener, and call the requestLocationUpdates on the LocationManager.

Here’s a code snippet:

    LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
      // Called when a new location is found by the network location provider.
      makeUseOfNewLocation(location);
    }

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

    public void onProviderEnabled(String provider) {}

    public void onProviderDisabled(String provider) {}
  };

// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);

Google’s API Guide on Location Strategies explains the code pretty nicely. But they also mention that in most cases, you’ll get better battery performance, as well as more appropriate accuracy, by using the Google Location Services API instead. Now the confusion starts!

  1. Google’s Location Services API

Google’s Location Services API is a part of the Google Play Services APK (here’s how to set it up) . They’re built on top of Android’s API. These APIs provide a “Fused Location Provider” instead of the providers mentioned above. This provider automatically chooses what underlying provider to use, based on accuracy, battery usage, etc. It is fast because you get location from a system-wide service that keeps updating it. And you can use more advanced features such as geofencing.

To use the Google’s Location Services, your app needs to connect to the GooglePlayServicesClient. To connect to the client, your activity (or fragment, or so) needs to implement GooglePlayServicesClient.ConnectionCallbacks and GooglePlayServicesClient.OnConnectionFailedListener interfaces. Here’s a sample code:

    public class MyActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener {
    LocationClient locationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        locationClient = new LocationClient(this, this, this);
    }

    @Override
    public void onConnected(Bundle bundle) {
    Location location = locationClient.getLastLocation() ;
        Toast.makeText(this, "Connected to Google Play Services", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onDisconnected() {
    Toast.makeText(this, "Connected from Google Play Services.", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        // code to handle failed connection
        // this code can be found here — http://developer.android.com/training/location/retrieve-current.html 
    }
  • Why is locationClient.getLastLocation() null?

The locationClient.getLastLocation() gets the last known location from the client. However, the Fused Location Provider will only maintain background location if at least one client is connected to it. Once the first client connects, it will immediately try to get a location. If your activity is the first client to connect and you call getLastLocation() right away in onConnected(), that might not be enough time for the first location to come in. This will result in location being null.

To solve this issue, you have to wait (indeterminately) till the provider gets the location and then call getLastLocation(), which is impossible to know. Another (better) option is to implement the com.google.android.gms.location.LocationListener interface to receive periodic location updates (and switch it off once you get the first update).

    public class MyActivity extends Activity implements ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
    // . . . . . . . . more stuff here 
    LocationRequest locationRequest;
    LocationClient locationClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // . . . . other initialization code
        locationClient = new LocationClient(this, this, this);
    locationRequest = new LocationRequest();
    // Use high accuracy
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // Set the update interval to 5 seconds
    locationRequest.setInterval(UPDATE_INTERVAL);
        // Set the fastest update interval to 1 second
    locationRequest.setFastestInterval(FASTEST_INTERVAL);
    }
    // . . . . . . . . other methods 
    @Override
    public void onConnected(Bundle bundle) {
        Location location = locationClient.getLastLocation();
        if (location == null)
            locationClient.requestLocationUpdates(locationRequest, this);
        else
            Toast.makeText(getActivity(), "Location: " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_SHORT).show();
    }
    // . . . . . . . . other methods
    @Override
    public void onLocationChanged(Location location) {
        locationClient.removeLocationUpdates(this);
        // Use the location here!!!
    }

In this code, you’re checking if the client already has the last location (in onConnected). If not, you’re requesting for location updates, and switching off the requests (in onLocationChanged() callback) as soon as you get an update.

Note that the locationClient.requestLocationUpdates(locationRequest, this); has to be inside the onConnected callback, or else you will get an IllegalStateException because you will be trying to request for locations without connected to the Google Play Services Client.

  • User has disabled Location Services

Many times, the user would have location services disabled (to save battery, or privacy reasons). In such a case, the code above will still request for location updates, but onLocationChanged will never get called. You can stop the requests by checking if the user has disabled the location services.

If your app requires them to enable location services, you would want to show a message or a toast. Unfortunately, there is no way of checking if the user has disabled location services in Google’s Location Services API. For this, you will have to resort back to Android’s API.

In your onCreate method:

    LocationManager manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && !manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
    locationEnabled = false;
    Toast.makeText(getActivity(), "Enable location services for accurate data", Toast.LENGTH_SHORT).show();
}
else locationEnabled = true;

And use the locationEnabled flag in your onConnected method like this:

    if (location != null) {
    Toast.makeText(getActivity(), "Location: " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_SHORT).show();
}
else if (location == null && locationEnabled) {
    locationClient.requestLocationUpdates(locationRequest, this);
}

UPDATE

Document is updated, LocationClient is removed and the api supports to enable GPS with one click from dialog:

task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
@Override
public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
    // All location settings are satisfied. The client can initialize
    // location requests here.
    // ...
}
});

task.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        if (e instanceof ResolvableApiException) {
            // Location settings are not satisfied, but this can be fixed
            // by showing the user a dialog.
            try {
                // Show the dialog by calling startResolutionForResult(),
                // and check the result in onActivityResult().
                ResolvableApiException resolvable = (ResolvableApiException) e;
                resolvable.startResolutionForResult(MainActivity.this,
                        REQUEST_CHECK_SETTINGS);
            } catch (IntentSender.SendIntentException sendEx) {
                // Ignore the error.
            }
        }
    }
});

Link https://developer.android.com/training/location/change-location-settings#prompt

New location client: FusedLocationProviderClient

  private FusedLocationProviderClient fusedLocationClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}

It is recommended to go through https://developer.android.com/training/location before doing any location tasks.


In my experience, "more appropriate accuracy" doesn't mean better by any means. Unless I'm missing something, if you want to make sure GPS is used, LocationManager is the only way to go. We track vehicles with our app and, again, unless I'm missing something, Google Play Services provides some very inaccurate locations quite often.


I have been using the Google Location Services API for quite a while. It does have advantages, since it encapsulates the complexity of having several sources for determining positions. However it encapsulates too heavily, so that when you get a strange position, you have no way to determine where that strange position came from.

In real life I have had several freak values pop up, being 10's of kilometers away from the actual position. The only explanation is that these crazy locations stem from errors in Googles Wi-Fi or NWK databases - errors which will always be there, since Wi-Fi and Network topologies change every day. But unfortunately (and surprisingly) the API gives you no information as to how an individual position was derived.

enter image description here

This leaves you with the problems of having to filter out freak values based on plausibility checking on speed, acceleration, bearing etc.

... or go back to the good old framework API and use GPS only, which is what I decided to do until Google improves the fused API.


You should use the Google Play Services location api instead of LocationManager. According to the docs:

The Google Play services location APIs are preferred over the Android framework location APIs (android.location) as a way of adding location awareness to your app. If you are currently using the Android framework location APIs, you are strongly encouraged to switch to the Google Play services location APIs as soon as possible.

As to why to switch, Google says this:

The Google Location Services API, part of Google Play Services, provides a more powerful, high-level framework that automatically handles location providers, user movement, and location accuracy. It also handles location update scheduling based on power consumption parameters you provide. In most cases, you'll get better battery performance, as well as more appropriate accuracy, by using the Location Services API.


The Google Location Services API, part of Google Play Services, provides a more powerful, high-level framework that automatically handles location providers, user movement, and location accuracy. It also handles location update scheduling based on power consumption parameters you provide. In most cases, you’ll get better battery performance, as well as more appropriate accuracy, by using the Location Services API.

More detailed diffferences between the two apis Google Play Service Location API and Android Framework Location API can be found here


Diffferences between the two apis Google Play Service Location API and Android Framework Location API based on GPS service

FusedLocationProviderClient

  1. For the 1st fetch, the location must not be null(i.e: Some other app need to update the Lastknown location in the GoogleplayService database. if it is null, need work around)
  2. For the next sequential Fetch, it uses requestLocationUpdates() method to fetch the location.
  3. The location fetch is only based on locationRequest.setInterval(milliseconds)and setFastestInterval(milliseconds), not based on user location change
  4. The LatLng value returned has contain only 7 decimal values (e.g: 11.9557996, 79.8234599), not as accurate
  5. Recommended, when your app requirement takes current location distance negligible of (50 - 100 meters accuracy)
  6. Effective in Battery usage.

LocationManager Api

  1. The user location fetch is invoked using locationManager.requestLocationUpdates()
  2. The location fetch based on user location change and time intervals locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, milliseconds, mindistance, Mylocationlistener)

  3. The LatLng value returned has contain 14 decimal values (e.g: 11.94574594963342 79.81166719458997) accurate location values

  4. Recommended for location based app, when needs more accuracy even in meters.
  5. Battery usage is based on fetch interval and fetch distance.

Yes, the Google Play Services Location Services API can give very misleading Location info. WiFi modems get moved, WiFi modems get updated with incorrect location information (ie if location is spoofed by an Android device that updates the WiFi modem's location) and there are a host of other circumstances that can result in incorrect Location data from WiFi modem triangulation. In all our apps where precise Location is mandatory, we use GPS only.