reading_notes

Read: 42 - Location

Mobile users take their devices with them everywhere, and adding location awareness to your app offers users a more contextual experience. The location APIs in Google Play services facilitate adding location awareness to app with automated location tracking, wrong-side-of-the-street detection, geofencing, and activity recognition.

Get the last known location

Using the Google Play services location APIs, your app can request the last known location of the user’s device. In most cases, you are interested in the user’s current location, which is usually equivalent to the last known location of the device. using fused location provider to retrieve the device’s last known location.

The fused location provider is one of the location APIs in Google Play services. It manages the underlying location technology and provides a simple API so that you can specify requirements at a high level, like high accuracy or low power. It also optimizes the device’s use of battery power.

Set up Google Play services

To access the fused location provider, your app’s development project must include Google Play services. Download and install the Google Play services component via the SDK Manager and add the library to your project. Setting Up Google Play Services.

Specify app permissions

Apps whose features use location services must request location permissions, depending on the use cases of those features.

Create Location Services Client

private FusedLocationProviderClient fusedLocationClient;

// ..

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}

Get The last known location

fusedLocationClient.getLastLocation()
        .addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                // Got last known location. In some rare situations this can be null.
                if (location != null) {
                    // Logic to handle location object
                }
            }
        });

The location object maybe null in these 3 cases

Choose the best location estimate