FusedLocationApi.getLastLocation always null

2020-01-24 04:21发布

I'd like to simply retrieve device location in my Android project and in order to do so I use the play-services approach:

            protected synchronized void buildGoogleApiClient() {

    mGoogleApiClient = new GoogleApiClient.Builder( MainSearchActivity.this )
        .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
            @Override
            public void onConnected( Bundle bundle ){
                Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
                if( location == null ){
                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            lastLocation = location;
                        }
                    });
                }
            }
            @Override
            public void onConnectionSuspended( int i ){

            }

        })
        .addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
            @Override
            public void onConnectionFailed( ConnectionResult connectionResult ){
                if( connectionResult.hasResolution() ){
                    try {
                        // Start an Activity that tries to resolve the error
                        connectionResult.startResolutionForResult(MainSearchActivity.this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                    }catch( IntentSender.SendIntentException e ){
                        e.printStackTrace();
                    }
                }else{
                    Utils.logger("Location services connection failed with code " + connectionResult.getErrorCode(), Utils.LOG_DEBUG );
                }
            }
        })
        .addApi(LocationServices.API)
        .build();

    mGoogleApiClient.connect();
}

public Location retrieveLastLocation(){
    Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if( loc == null)
    {

    }
    return loc; //TODO: What if loc is null?
}

but the loc variable is ALWAYS null. It's as such on different phones, every single time. Also lastLocation, that I try to assign in the onLocationChanged, never changes. Always null.

These are the permission I set for the app

    <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

I just don't get it: why can't the LocationServices retrieve a position? I have all geolocation settings enabled on all three the deviced i tested upon :-/

Thank you for any help

9条回答
时光不老,我们不散
2楼-- · 2020-01-24 04:52

As in this post said, The fused Location Provider will only maintain background location if at least one client is connected to it.

But we don't want to launch the Maps app to get last location, and also we can't say our users to launch Maps app to get last location.

What we need to do is

  1. We have to request location update from FusedLocationProviderClient
  2. Then we can get the last location from FusedLocationProviderClient, it wouldn't be null.

Request Location

LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(60000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        if (locationResult == null) {
            return;
        }
        for (Location location : locationResult.getLocations()) {
            if (location != null) {
                //TODO: UI updates.
            }
        }
    }
};
LocationServices.getFusedLocationProviderClient(context).requestLocationUpdates(mLocationRequest, mLocationCallback, null);

Get last location

LocationServices.getFusedLocationProviderClient(context).getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
        @Override
        public void onSuccess(Location location) {
            //TODO: UI updates.
        }
    });

For best result onStart of the Activity request for location update, and then you can get last location.

查看更多
beautiful°
3楼-- · 2020-01-24 04:52

This is related to Amit K. Saha's answer but for me, on one of my Lollipop devices I kept getting null. So I opened up the maps app and I got the screen below asking me to turn on all that jazz to improve my location.

Once I did that once, my device was able to receive the location with just one call to getLastLocation();

I presume then one would have to ask for these permissions on app install for users who may not have used their maps app yet.

enter image description here

查看更多
够拽才男人
4楼-- · 2020-01-24 04:55

Here is the exact answer and explanation.

LocationClient getLastLocation() return null

查看更多
登录 后发表回答