问题
What would be the "right" way to get the last known location on Android using LocationClient (v2 API) in a synchronous manner?
UPDATE
This is the best I've come up with (it's not synchronous but it overcomes the burden of dealing with connect() and onConnected() each time the last known location is needed):
public enum SystemServicesNew implements GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
INSTANCE;
private LocationClient mLocationClient;
private Location mLastKnownLocation;
static {
INSTANCE.mLocationClient = new LocationClient(MyApp.getAppContext(), INSTANCE, INSTANCE);
INSTANCE.mLastKnownLocation = new Location("");
INSTANCE.mLastKnownLocation.setLatitude(0);
INSTANCE.mLastKnownLocation.setLongitude(0);
INSTANCE.getLastKnownLocation(); // fire it already so subsequent calls get the real location
}
public Location getLastKnownLocation()
{
if(!mLocationClient.isConnected()) {
mLocationClient.connect();
return mLastKnownLocation;
}
mLastKnownLocation = mLocationClient.getLastLocation();
return mLastKnownLocation;
}
@Override
public void onConnected(Bundle bundle) {
Toast.makeText(MyApp.getAppContext(), "LocationClient:Connected", Toast.LENGTH_SHORT).show();
}
@Override
public void onDisconnected() {
Toast.makeText(MyApp.getAppContext(), "LocationClient:Disconnected", Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(MyApp.getAppContext(), connectionResult.toString(), Toast.LENGTH_SHORT).show();
}
}
My Java skills are... less developed... any improvement suggestions?
回答1:
A legitimate way of doing this is to use LocationClient's
getLastLocation()
If you want to do it in a synchronous manner, you should keep in mind that it will not be a precise location, and in rare cases it may even be unavailable. Check the documentation below:
public Location getLastLocation ()
Returns the best most recent location currently available.
If a location is not available, which should happen very rarely, null will be returned. The best accuracy available while respecting the location permissions will be returned.
This method provides a simplified way to get location. It is particularly well suited for applications that do not require an accurate location and that do not want to maintain extra logic for location updates.
来源:https://stackoverflow.com/questions/21903415/get-the-last-known-location-on-android-synchronously