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.
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.
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.
Apps whose features use location services must request location permissions, depending on the use cases of those features.
private FusedLocationProviderClient fusedLocationClient;
// ..
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
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
}
}
});
getLastLocation()
gets a location estimate more quickly and minimizes battery usage that can be attributed to your app. However, the location information might be out of date, if no other clients have actively used location recently.getCurrentLocation(
) gets a fresher, more accurate location more consistently. However, this method can cause active location computation to occur on the device