LocationManager和LocationClient一起获取用户位置

And*_*son 8 android location

我只需要获取用户位置.优选地,确切的位置,但如果不可能,粗略的位置将是好的.

根据文件:

LocationClient.getLastLocation()

Returns the best most recent location currently available.

LocationManager.getLastKnownLocation(字符串)

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

如果我的理解是对的,那么前者会给我一个非常好的结果(或者有时为空),而后者会给我一个很少会为空的结果.

这是我的代码(简化)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

它似乎工作,但我的问题是:

  1. 我的理解getLastLocationgetLastKnownLocation正确吗?
  2. 这是一个好方法吗?
  3. 我可以在同一活动中同时使用两者吗?

谢谢

Joe*_*lin 7

LocationClient.getLastLocation()null在无法确定位置修复时返回.getLastLocation()没有更糟糕的getLastKnownLocation(),通常要好得多.我不认为getLastKnownLocation()像你一样"退回" .

使用两者都不会遇到麻烦,但这太过分了.

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

Google Play服务的文档更详细地讨论了这一点.