Leem.fin
Leem.fin

Reputation: 42622

Get last known location with Google Service API

I am learning getting location with Google Service API. But I am getting confused since I saw people use two ways to get location:

1.

FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;
Location lastKnownLocation = fusedLocationProviderApi.getLastLocation(googleApiClient);

2.

FusedLocationProviderClient mFusedLocationClient =  LocationServices.getFusedLocationProviderClient(this);
...
Task<Location> locationTask = mFusedLocationClient.getLastLocation();
        locationTask.addOnSuccessListener(this, new OnSuccessListener<Location>() {
            @Override
            public void onSuccess(Location location) {
                // Got last known location
                if (location != null) {
                    mLastKnownLocation = location;
                }
            }
        });

Could someone please explain to me when to use which one & what are the differences between these two approaches to get last known location?

Upvotes: 1

Views: 2117

Answers (2)

blackkara
blackkara

Reputation: 5052

Both getLastLocation methods point us same documentation content. But using the new FusedLocationProviderClient is simpler than FusedLocationProviderApi, because we don't deal with google api client and it's callback methods. It handles play services connection for us automatically. Just it

FusedLocationProviderClient methods return Task(even getting last known location), IMHO this is due to handling play services things internally.

Upvotes: 1

Jarvis
Jarvis

Reputation: 1792

In Android blog-spot google had posted one topic on location access.

Reduce friction with the new Location APIs

In that google are saying that not to use GoogleApiClient.

In the link they have details explanation.

Now the code works, but it's not ideal for a few reasons:

  • It would be hard to refactor into shared classes if, for instance, you wanted to access Location Services in multiple activities.
  • The app connects optimistically in onCreate even if Location Services are not needed until later (for example, after user input).
  • It does not handle the case where the app fails to connect to Google Play services.
  • There is a lot of boilerplate connection logic before getting started with location updates.

A better developer experience

The new LocationServices APIs are much simpler and will make your code less error prone. The connection logic is handled automatically, and you only need to attach a single completion listener:

Upvotes: 0

Related Questions