Jon Rumsey

An online markdown blog and knowledge repository.


Project maintained by nojronatron Hosted on GitHub Pages — Theme by mattgraham

Read Class 39: Location

Get Last Known Location

Acquried via the Google Play Services "Location API".

Last Known Location is assumed to be equivalent to Current Location.

Fused Location Provider: Actual component that retrieves location data. Manages underlying location technology. Provdies simple API to specify high accuracy while using minimal power.

Utilize getLastLocation() to acquire location information from Fused Location Provider.

Overview of Steps

  1. App Dev project must include Google Play Services. Download this via SDK Manager and add the Library to the Project. deprecated.
  2. Apps using location must "request location permissions" from Android.
  3. Create Location Services Client within the onCreate() method fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
  4. Getting last known location of the device via getLastLocation() method which returns a Task.
  5. Use Task to reference lattitude and longitude via the Location object (which could be null if: Off; Never recorded location to begin with; Fused Location Provider hasn't requested location since last restart).
  6. Select a location estimate using the FusedLocationProviderClient i.e.: getLastLocation() which minimizes battery usage, or getCurrentLocation() which causes active processing of location determination, utilizing more battery power.

Avoid using requestLocationUpdates() as it is a power-hungry process and could linger in memory if not closed properly, further draining battery power.

Code Samples

As they existed at developer.android.com when accessed...

Adding to the onCreate() method:

private FusedLocationProviderClient fusedLocationClient;

// ..

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

    fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}

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

Additional Development Resources

When building location-aware Apps:

Internet Resources

Get Last Known Location from Developer Android Docs

Return to Root Readme