1

嘿伙计们,我想获取用户位置的纬度和经度。我已经尝试过开发人员站点和堆栈溢出,有很多针对移动用户的示例,它们使用以下内容:- onLocationChanged() 我不需要更新位置,用户只需打开一两分钟,所以我需要在应用程序启动时找到位置,如果用户之前从未使用过任何地理定位应用程序怎么办,因此我也想要 LocationManager.getLastKnownLocation() 的替代方案

我的代码是:-

LocationManager lm = (LocationManager)
        getSystemService(Context.LOCATION_SERVICE);
        // connect to the GPS location service
        Location loc = lm.getLastKnownLocation(lm.NETWORK_PROVIDER);
        Toast.makeText(currentLocation.this, "Latitude -> "+Double.toString(loc.getLatitude())
                +" Longitude is -> "+Double.toString(loc.getLongitude()), Toast.LENGTH_LONG).show();

并且工作正常。但我担心第一次使用 getLastKnownLocation 可能会返回 null。

谢谢

4

1 回答 1

3

注册位置更新,一旦您收到第一个更新,您可以取消注册以获取未来的更新。

换句话说,创建一个并用你的方法LocationListener注册它。在你的方法中,调用你的方法,作为参数。LocationManagerrequestLocationUpdatesonLocationChangedLocationListenerremoveUpdatesLocationManagerthis

在获得新位置之前可能需要一些时间,但除了使用之外,getLastKnownLocation没有其他选择。

于 2011-03-16T20:42:36.397 回答