大家好 我想获取用户位置的纬度和经度。 我已经尝试过开发者网站和堆栈溢出,有大量针对移动用户的示例使用了一些东西,比如:- 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。
谢谢
最佳答案
注册位置更新,一旦收到第一个更新,您就可以取消注册以后的更新。
换句话说,创建一个 LocationListener
并将其注册到您的 LocationManager
的 requestLocationUpdates
方法。在 LocationListener
的 onLocationChanged
方法中,调用 LocationManager
的 removeUpdates
方法,使用 this
作为参数。
您可能需要一些时间才能找到新位置,但除了使用 getLastKnownLocation
之外,别无选择。
关于android - 如何在Android上获取当前位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5331369/