如何在Android上获取当前位置
嘿伙计们 我想获取用户位置的纬度和经度。 我尝试过开发人员网站和堆栈溢出,有很多针对移动用户的示例,它们使用以下内容:- 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。
谢谢
Hey guys
i want to get the latitude and longitude of the users location.
I have tried developers site and stack overflow , there are loads of examples targeted on the moving user which use some thing like :-
onLocationChanged()
I dont need updates of the location , the user will just open it for a minute or two
so i need to find the location the time the application starts and what if the user has never used any geolocation app before hence i would also like an alternative for
LocationManager.getLastKnownLocation()
My code is :-
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();
and is working fine.
But i am scared that the getLastKnownLocation may return null when used for first time.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
注册位置更新,收到第一个更新后,您可以取消注册以获取未来的更新。
换句话说,创建一个
LocationListener
并使用LocationManager
的requestLocationUpdates
方法注册它。在LocationListener
的onLocationChanged
方法中,使用this< 调用
LocationManager
上的removeUpdates
方法/code> 作为参数。您可能需要一些时间才能获得新位置,但除了使用
getLastKnownLocation
之外,实际上没有其他选择。Sign up for location updates and once you receive the first update, you can unregister for future updates.
In other words, create a
LocationListener
and register it with yourLocationManager
'srequestLocationUpdates
method. In theonLocationChanged
method of yourLocationListener
, call theremoveUpdates
method on yourLocationManager
, withthis
as parameter.It might take some time before you get a new location, but except for using
getLastKnownLocation
there's not really an alternative.