GetLastLocation always returns null

2019-08-19 10:24发布

问题:

I try to access the last known location in a Fragment as explained here

in my onCreate:

public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
}

in my onResume:

@Override
public void onResume() {
    super.onResume();
    mGoogleApiClient.connect();
}

The Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener

and the on Connected is called!!

@Override
public void onConnected(Bundle bundle) {
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
    }
}

and the mLastLocation is always null. Everytime I try to call GetLastLocation() it returns null.

Any idea why?

回答1:

I never tried that approach, I usually create a LocationProvider that implements LocationsSource and LocationListener. Here's an example that may help you with this approach: How to get My Location changed event with Google Maps android API v2?