reading-notes

View on GitHub

Location

One of Google play sevices APIs is the location, you can use this api to get the last known location.

to start, first add google play location service dependency in gradle.build

  implementation 'com.google.android.gms:play-services-location:18.0.0'

to get the location, you must add the permission of reading permissions in the Manifest.xml file:

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

since you can’t get user’s location without his permission, so you need to ask for the permission in the run time to do so, do the following:

Create location services client

  private FusedLocationProviderClient fusedLocationClient;

// ..

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

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}

Get the latest know location using getLastLocation() method

  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
                }
            }
        });

you need to check if the location is null because this may happen in the following scenarios:

sometimes you may need the best estimation of the location, do so by applying the following: