LocationClient does not update getLastLocation() o

2019-07-30 13:15发布

问题:

I'm using the google play services api to get location updates in my app. However, for some reason, client.getLastLocation() doesn't changes its value when a client is connected. Only after requesting location updates by registering a listener will the location change. I think it may be an emulator only problem, but even when I manually change the location using ddms or telnet, the value of getLastLocation() still doesn't change.

Unfortunately, my phone isn't showing up in adb, so I can't test it on an actual device, but does anyone have any ideas as to why this would happen? It's not that big of a deal because I can solve it by requesting location updates, but I would like to provide a setting to allow users to manually update their location instead of having it uploaded every few seconds. Some code to show what I'm talking about.

@Override
public void onClick(View v) {
    Location newLocation = client.getLastLocation();
    if(newLocation == null)
    {
        Toast.makeText(getActivity(), "Finding location", Toast.LENGTH_SHORT).show();
        return;
    }
    if(distanceSignificant(currentLocation, newLocation))
    {
        currentLocation = newLocation;
        Log.d(TAG, "distance significant, updating location");
            uploadNewLocation();
        }
    }
});

Every time I click that button, the location will be the same as what it was last.

@Override
public void onConnected(Bundle data) {
    Log.d(TAG, "connected to locations");
    Toast.makeText(getActivity(), "Starting location services", Toast.LENGTH_SHORT).show();
    currentLocation = client.getLastLocation();

    if(currentLocation == null)
    {
        Log.d(TAG, "can't add user location yet, not available");
    }

    if(shouldUpdate)
    {
        client.requestLocationUpdates(locationRequest, this);
        updateButton.setVisibility(View.GONE);
    }
    else
    {
        updateButton.setVisibility(View.VISIBLE);
    }

}

In this case, shouldUpdate is set in onCreateView and is set by a user setting.

Does anyone know what I should do to fix this? I feel like I'm missing something simple.

回答1:

This happens because getLastLocation is a non-blocking, pro-battery call to get the last known location (this might be old value) and when nothing is actively retrieving location updates it won't be magically changed.

The best thing you can do to get location on user request is starting requesting location updates and stopping it when you get the first location.