Android 获取位置或提示启用位置服务(如果禁用)
我发现这个答案的一些片段散布在其他帖子中,但我想在这里记录下来供其他人使用。
我如何简单地请求用户的 GPS 和/或网络位置,并且如果他们尚未启用该服务,则提示他们这样做?
I've found bits and pieces of this answer scattered through other posts, but I wanted to record it here for others.
How can I simply request the user's GPS and/or Network location and, if they haven't enabled the service, prompt them to do so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想通过按下按钮来捕获位置,请按以下方法操作。如果用户没有启用位置服务,这会将他们发送到设置菜单以启用它。
首先,您必须将权限“android.permission.ACCESS_COARSE_LOCATION”添加到清单中。如果您需要GPS(网络位置不够敏感),请添加权限“android.permission.ACCESS_FINE_LOCATION”,并将“Criteria.ACCURACY_COARSE”更改为“Criteria.ACCURACY_FINE”
我的外部类设置了此侦听器
然后,每当你想停止收听时,请拨打此电话。您至少应该在活动的 onStop 方法期间进行此调用。
If you want to capture the location on a button push, here's how you'd do it. If the user does not have a location service enabled, this will send them to the settings menu to enable it.
First, you must add the permission "android.permission.ACCESS_COARSE_LOCATION" to your manifest. If you need GPS (network location isn't sensitive enough), add the permission "android.permission.ACCESS_FINE_LOCATION" instead, and change the "Criteria.ACCURACY_COARSE" to "Criteria.ACCURACY_FINE"
My outer class has this listener set up
Then, whenever you want to stop listening call this. You should at least make this call during your activity's onStop method.
在查阅了 Stack Overflow 上的大量答案后,我发现这种方法工作得非常好,甚至不需要很多代码。
声明
int GPSoff = 0
作为全局变量。现在,无论您需要检查 GPS 的当前状态并重新引导用户打开 GPS,都可以使用以下命令:
After going through a lot of answers on Stack Overflow, I found this method to work perfectly fine and doesn't even require a lot of code.
Declare
int GPSoff = 0
as a global variable.Now wherever you need to check for the present status of the GPS and re-direct the user to turn the GPS on, use this :
要提示用户启用位置服务,您应该使用 google play 服务中包含的新 LocationRequest,您可以在 位置请求
To prompt the user to enable location services you should use the new LocationRequest included in google play services, you can found the complete guide in LocationRequest