The NEW Android Location API

Android | Tuesday September 2 2014 11:18 | Comments (3)

Since the release of the new Google Play Services 4.2, some new APIs have been added and Google have changed their Client API Model. One such API model to be affected is the Location API.

If you are targeting the latest version of Android in your app, you will see that your existing Location API code will now be flagged as being deprecated.

Previously, you would interact with the Location API as follows:

    LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    String provider = locationManager.getBestProvider(criteria, false);
    locationManager.requestLocationUpdates(provider, updateInterval, 0, this);

    ....
    public void onLocationChanged(Location location) {
        //Handle location update
    }

Now with the new Location API, it will look similar to this:

    GoogleApiClient mGoogleApiClient;
    LocationRequest mLocationRequest;
    ...
    mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addApi(LocationServices.API)
    .addConnectionCallbacks((GoogleApiClient.ConnectionCallbacks) this)
    .addOnConnectionFailedListener(this)
    .build();

    ....
    public void onConnected(Bundle arg0) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

        ...
    public void onLocationChanged(Location location) {
        //Handle location update
    }

You’ll need to import:
com.google.android.gms.location.LocationServices (thanks Mark)
com.google.android.gms.common.api.GoogleApiClient;
com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener
(note it’s the GoogleApiClient, instead of the GooglePlayServicesClient version).

As well as LocationListener, your class also needs to implement ConnectionCallbacks and OnConectionFailedListener (assuming the same class is handling all the callbacks).

Also, onDisconnected() has been renamed to onConnectionSuspended(int cause).