Receiving regular Location Updates in Android

A few apps require regular location updates so as to present accurate information to users. For example a taxi app, which constantly updates user & cab driver’s current location.

While you can get a device’s location by calling the getLastLocation() method, as illustrated in the tutorial Getting the last known location, a better approach will be to get regular location updates.

This lesson shows you how to request regular updates about a device’s location using the requestLocationUpdates() method in the fused location provider.

Getting the Last Known Location


Obtaining last known location of the device will be a good start before initiating periodic location updates. For this, we need to first request location permission for the app. This can be done by adding the below mentioned code in the manifest file of the app project-

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.techhiking.locationupdate">

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

Go through the tutorial to know more about these permissions and to know how to get the last known location of the device.

Request Location Updates


Before requesting location updates, your app must connect to location services and make a location request. To make a location request, add the following code in your MainActivity.

protected void createLocationRequest() {
    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(5000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

You can change the priority and interval time as per your app’s requirement.

Getting Current Location Settings


Once you have connected to Google Play services and the location services API, you now need to get the current location settings of the user’s device.To do so, add the following code:

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
     .addLocationRequest(mLocationRequest);

Next check whether the current location settings are satisfied:

PendingResult<LocationSettingsResult> result =
         LocationServices.SettingsApi.checkLocationSettings(mGoogleClient,
                 builder.build());

when the pendingResult returns, you can check the current location settings by checking the returned status code from the LocationSettingsResult object.

Prompt the User to Change Location Settings


To find out whether the current location setting is appropriate for the application, you can analyze the status code. If the current location setting isn’t appropriate, you can prompt a dialog box for the user asking them to change the location preference by calling startResolutionForResult(Activity, int).

result.setResultCallback(new ResultCallback&lt;LocationSettingsResult&gt;()) {
     @Override
     public void onResult(LocationSettingsResult result) {
         final Status status = result.getStatus();
         final LocationSettingsStates = result.getLocationSettingsStates();
         switch (status.getStatusCode()) {
             case LocationSettingsStatusCodes.SUCCESS:
                 // All location settings are satisfied. The client can
                 // initialize location requests here.
                 ...
                 break;
             case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                 // 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().
                     status.startResolutionForResult(
                         OuterClass.this,
                         REQUEST_CHECK_SETTINGS);
                 } catch (SendIntentException e) {
                     // Ignore the error.
                 }
                 break;
             case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                 // Location settings are not satisfied. However, we have no way
                 // to fix the settings so we won't show the dialog.
                 ...
                 break;
         }
     }
 });

Request Location Updates


Once the location setting is as per your application’s preference, you can now move forward to get location change updates. But before requesting location updates, your app must connect to location services and make a location request. Do this by adding the following code snippet-

@Override
public void onConnected(Bundle connectionHint) {
    ...
    if (mRequestingLocationUpdates) {
        startLocationUpdates();
    }
}

protected void startLocationUpdates() {
    LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
}

Defining the Location Update Callback


You can now requested location updates. But you need a receiver to get these triggers. Implement the LocationListener interface in your activity and override its onLocationChanged() method to receive these Locations.

public class MainActivity extends ActionBarActivity implements
        ConnectionCallbacks, OnConnectionFailedListener, LocationListener {
    ...
    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
        updateUI();
    }

    private void updateUI() {
        mLatitudeTextView.setText(String.valueOf(mCurrentLocation.getLatitude()));
        mLongitudeTextView.setText(String.valueOf(mCurrentLocation.getLongitude()));
        mLastUpdateTimeTextView.setText(mLastUpdateTime);
    }
}

Stopping Location Updates


If you want to stop these location updates when the activity is not in the foreground, you can write the following code :

@Override
protected void onPause() {
    super.onPause();
    stopLocationUpdates();
}

protected void stopLocationUpdates() {
    LocationServices.FusedLocationApi.removeLocationUpdates(
            mGoogleApiClient, this);
}

Leave a Reply

Your email address will not be published. Required fields are marked *