android - 同步获取 Android 上的最后已知位置

标签 android location

同步方式使用 LocationClient (v2 API) 在 Android 上获取最后已知位置的“正确”方法是什么?


更新

这是我想出的最好的(它不是同步的,但它克服了每次最后一次处理 connect()onConnected() 的负担需要已知位置):

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();
    }
}

我的 Java 技能……欠发达……有什么改进建议吗?

最佳答案

这样做的合法方法是使用 LocationClient 的

getLastLocation()

如果您想以同步方式进行,您应该记住它不会是一个精确的位置,在极少数情况下甚至可能不可用。检查以下文档:

public Location getLastLocation ()

返回当前可用的最佳最近位置。

如果位置不可用(这种情况很少发生),将返回 null。将返回在尊重位置权限的情况下可用的最佳准确度。

此方法提供了一种获取位置的简化方法。它特别适合不需要准确位置并且不想为位置更新维护额外逻辑的应用程序。

关于android - 同步获取 Android 上的最后已知位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21903415/

相关文章:

Android 开发,源文件组织/符号最佳实践?

Javascript 正则表达式检查 URL 是否包含一个词并且不包含另一个词

共享位置数据的 iOS 应用

android - ClassCastException 类扩展了 android.location.Location

java - React Native - 如何将可读数组从 React Native 映射到 Android 中的 native 模块?

java - android布局,有面板吗?

android - Android 的位置选取器

安卓 :How to get Current Location in Longitude and latitude?

android - @StringRes、@DrawableRes、@LayoutRes 等 android 注解 lint 检查与 kotlin 参数

jquery - 使用 jQuery/Phonegap 的 Soap 查询在 Android 上总是失败