Android - 仅获取一次位置
我需要获取 Android 应用程序上的当前用户位置,因此我在网上阅读了一些教程和示例,但我看到在所有示例中,位置都是从“onLocationChange”中检索的,这意味着每次位置改变时,执行“onLocationChange”中的代码。
我只需要在应用程序启动时获取用户位置。
感谢您的帮助!
i need to get the current user location on an android app, so i've read some tutorials and samples on the web, but i see that in all the examples, the location is retrived from a "onLocationChange" that mean that every time the location change, the code in the "onLocationChange" is executed.
i need only to get the user location at the moment the app is started.
Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您可以使用下面的代码获取最后知道的位置。它获取位置提供程序并向后循环数组。即从 GPS 开始,如果没有 GPS,则获取网络位置。当您需要获取位置时,您可以调用此方法。
You can get the last know location using the code below. It gets the location providers and loops over the array backwards. i.e starts with GPS, if no GPS then gets network location. You can call this method whenever you need to get the location.
您可以使用 LocationManager 来执行此操作。getLastKnownLocation< /a>
You can do this with LocationManager.getLastKnownLocation
使用 LocationManager.requestSingleUpdate()
看一下: http://developer.android.com/reference/android/location/LocationManager.html#requestSingleUpdate%28java.lang.String,%20android.location.LocationListener,% 20android.os.Looper%29
use LocationManager.requestSingleUpdate()
look at: http://developer.android.com/reference/android/location/LocationManager.html#requestSingleUpdate%28java.lang.String,%20android.location.LocationListener,%20android.os.Looper%29
将其放入主活动中:
将相同的内容放入 onResume() 中;
Put this in the main activity:
Put the same in the onResume();
为了使 Phobos 提议的 getGPS() 方法正常工作,您必须在 AndroidManifest.xml 中允许访问,
这将消除接收 0.0 的错误
添加这些行:
For the
getGPS()
method which Phobos proposed to work properly you have to allow access within your AndroidManifest.xmlThat will get rid of your error of receiving 0.0
Add these lines:
您可以使用此方法从所有提供商处获取最佳位置。
首先创建一个名为FetchLocation的类,
然后创建一个OnLocationFetchListner接口!
然后你可以在代码中的任何地方调用这个方法!
您必须将其添加到 AndroidManifest.xml 中
You can get the best location from all providers using this method.
First create a class which is called FetchLocation
Then you create a OnLocationFetchListner interface!
Then you can call this method anywhere in your code!
And the you have to add this in the AndroidManifest.xml