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