【发布时间】: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;
}
}
它似乎有效,但我的问题是:
- 我对@987654326@ 和
getLastKnownLocation的理解是否正确? - 这是一个好方法吗?
- 我会在同一个活动中同时使用这两种方法有问题吗?
谢谢
【问题讨论】: