Get the last known location on Android synchronously

血红的双手。 提交于 2020-01-13 14:06:24

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!