1
我是新来的Android的发展,下面是我的代码对使用地理编码器来获取当前位置的城市名称,它返回null:Android的地理编码器返回无效的城市名称
私人无效updateCurrentLocation(位置定位){ 双LAT = 0.0,lng = 0.0;
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Log.i("tag", "Latitute is" + lat + ", Longtitute is" + lng);
} else {
City_Name = "Unavailable";
}
List<Address> list = null;
Geocoder geocoder = new Geocoder(this.getActivity());
try {
list = geocoder.getFromLocation(lat, lng, 1);
} catch (IOException e) {
e.printStackTrace();
}
//may provide multiple locations.
if (list != null && list.size() > 0) {
Address address = list.get(0);
City_Name = address.getLocality();
}
Log.i("Try", "CityName:" + City_Name);
//send empty message
handler.sendEmptyMessage(1);
}
我打开了GPS服务,已经在Manifest中添加了ACCESS_FINE_LOCATION和INTERNET权限。另外,我在Stackoverflow中搜索了有关Geocoder返回null的类似问题,但还没有找到有用的解决方案。其中之一是从Geocoder网站分析JSON,但它也不起作用。
任何人都可以帮忙吗?谢谢!顺便说一下,有没有更好的解决方案来获得城市名称?谢谢!
您的代码是否抛出IOException? – josemgu91
如果您在设备API 23或更高版本上进行测试,则需要提示权限,否则默认情况下会禁用该权限。一个快速的解决方法是批准从设置>应用程序>“应用程序名称”权限>权限 – MoGa
@ josemgu91不,它运作良好,但没有任何返回值。 – LunarS