【问题标题】:LocationManager and LocationClient together to get user locationLocationManager 和 LocationClient 一起获取用户位置
【发布时间】:2013-06-25 17:56:41
【问题描述】:

我只需要获取用户位置。最好是确切的位置,但如果不可能,粗略的位置就可以了。

根据文档:

LocationClient.getLastLocation()

Returns the best most recent location currently available.

LocationManager.getLastKnownLocation(String)

Returns a Location indicating the data from the last known location fix obtained from the given provider.

如果我的理解是正确的,前者会给我一个很好的结果(有时是 null),而后者会给我一个很少为 null 的结果。

这是我的代码(简化版)

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationClient = new LocationClient(this, this, this);

@Override
public void onConnected(Bundle dataBundle) {
    setUserLocation();
}

private void setUserLocation() {
    myLocation = locationClient.getLastLocation();

    if (myLocation == null) {
        myLocation = locationManager.getLastKnownLocation(locationManager.getBestProvider(new Criteria(), false));
        if (myLocation == null) {
            //I give up, just set the map somewhere and warn the user.
            myLocation = new Location("");
            myLocation.setLatitude(-22.624152);
            myLocation.setLongitude(-44.385624);
            Toast.makeText(this, R.string.location_not_found, Toast.LENGTH_LONG).show();
        }
    } else {
        isMyLocationOK = true;
    }
}

它似乎有效,但我的问题是:

  1. 我对@9​​87654326@ 和getLastKnownLocation 的理解是否正确?
  2. 这是一个好方法吗?
  3. 我会在同一个活动中同时使用这两种方法有问题吗?

谢谢

【问题讨论】:

    标签: android location


    【解决方案1】:

    LocationClient.getLastLocation() 仅在无法确定位置修复时返回 nullgetLastLocation() 并不比getLastKnownLocation(),而且通常要好得多。我认为不值得像你那样“退回”到getLastKnownLocation()

    两者都用不会有麻烦,但有点过头了。

    当然,您必须记住,LocationClientGoogle Play 服务 的一部分,因此它仅适用于平台包括 Google Play 商店的设备。某些设备可能使用非标准版本的 Android,您将无法访问LocationClient

    Google Play 服务的文档对此进行了更详细的讨论。

    【讨论】:

    • 很高兴知道!我已经有了处理 Google Play 可用性的代码(事实上,如果没有它,应用程序可能无法运行)。起初我只使用 LocationServices,但很多时候我得到了奇怪的结果。切换到 LocationClient 给了我更好的结果,但在许多情况下我无法重现的结果为空。我认为 Android 系统可能会在某个地方记录最后一个已知位置,该位置只能由 LocationService 类访问,因此我的代码在上面。如果不是这样,那么最好只依赖LocationClient,对吧?
    猜你喜欢
    • 2013-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    相关资源
    最近更新 更多