我是Android开发的新手,以下是关于使用Geocoder获取当前位置的城市名称的代码,它返回null:

private void updateCurrentLocation(Location location){double 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

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,但它也不起作用 .

有人能帮忙吗?谢谢!顺便说一句,有没有更好的解决方案来获得城市名称?谢谢!

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐