Android Get latitude and longitude with location manager(Android 使用位置管理器获取经纬度)
问题描述
我正在尝试使用位置管理器获取用户位置,但该位置始终返回 null.我还要求用户打开 gps.
I'm trying to get the user location with location manager but the location always returns null. I also am asking to the user to turn on the gps.
这是我的代码:
int permisioncheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION);
if(permisioncheck == 0){
lm = (LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location location = lm.getLastKnownLocation(provider);
if (location == null) {
continue;
}
if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = location;
}
}
if(bestLocation == null){
System.out.println("is NULL!");
}
}else{
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
希望有人能帮我找出错误,谢谢.
I hope that someone could help me to find the error, thanks.
推荐答案
错误"是您假设 getLastKnownLocation()
将返回 Location
.通常,它会返回 null
.使用 getLastKnownLocation()
作为可能的优化,否则您需要 requestLocationUpdates()
,然后使用 onLocationChanged()
方法中的位置.
The "error" is that you are assuming that getLastKnownLocation()
will return a Location
. Frequently, it will return null
. Use getLastKnownLocation()
as a possible optimization, but otherwise you need to requestLocationUpdates()
, then use the location in the onLocationChanged()
method.
查看这个示例项目和文档了解更多信息.
这篇关于Android 使用位置管理器获取经纬度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Android 使用位置管理器获取经纬度


- 获取数字的最后一位 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 转换 ldap 日期 2022-01-01