【发布时间】:2016-11-26 22:56:11
【问题描述】:
我是Android开发新手,下面是我使用Geocoder获取当前位置城市名称的代码,它返回null:
private void updateCurrentLocation(Location location) { 双纬度 = 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?
-
如果是在API 23及以上的设备上测试,需要提示权限,否则默认禁用。一个快速的解决方法是从设置>应用>“应用名称”>权限批准权限
-
@josemgu91 不,它运行良好,但没有任何返回值。
-
@MoGa 让我仔细检查一下。谢谢。
-
它返回一个空值还是一个空列表?因为如果 getFromLocation 方法没有得到你的位置,它可以返回一个空集。
标签: android location google-geocoder android-gps