我正在尝试使用NETWORK_PROVIDER获取国家/地区名称,我写了一个方法
private int getCurrentLocation(Location location) throws IOException {
Geocoder geocoder = new Geocoder(this, getResources().getConfiguration().locale);
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 5);
String CurrentCountryFullName = addresses.get(0).getCountryName();
if (CurrentCountryFullName != null) {
for (StandartCurrency standartCurrency: RecourcesForStandartCurrencies.getStandartCurrencyList()){
if (RecourcesForStandartCurrencies.getCountryFullName(standartCurrency.getPosition()).toLowerCase().contains(CurrentCountryFullName.toLowerCase()))
return standartCurrency.getPosition();
}
}
return AddedCurrency.getAddedCurrenciesCount();
}
我从
调用此方法 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
leftFieldIndex = getCurrentLocation(locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER));
} catch (IOException e) {
e.printStackTrace();
我的AdnroidManifest.xml包含
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
我正在测试Nexus 4,它与工作互联网有wifi连接,但仍无法正常工作。
答案 0 :(得分:4)
Geocoder
不稳定,有时会停止工作。您没有发布错误日志或异常,但根据经验,当Geocoder
中断时,它只返回一个空列表。遗憾的是,无法检查Geocoder
是否提前工作(只有一种方法可以检查Geocoder
是否可用,即使它不起作用也会返回true)
当您的Geocoder
返回空列表时,解决方法是连接到Google Maps网络API。请查看this post以获取代码示例。您几乎要检查Geocoder
返回的列表是否为空或先为空,如果是AsyncTask
来对Google Maps API进行网络API调用。最终结果是相同的,因此您不应注意功能上的差异。
private int getCurrentLocation(Location location) throws IOException {
Geocoder geocoder = new Geocoder(this, getResources().getConfiguration().locale);
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 5);
if(addresses != null && addresses.size() > 0 {
//use addresses
} else {
//call web API async task
}
}
根据您对地址的处理方式,将Geocoder
实施分解为单独的类可能是有意义的。这样,您就可以使用Interface
将Geocoder
课程与您的活动或片段相关联,并在AsyncTask
网络电话和Geocoder
之间进行无缝转换工作(显然你不能在同一个方法中返回AsyncTask
的结果,因为它在方法完成时没有传递)
答案 1 :(得分:0)
我遇到了同样的问题,我转而使用v3 web API。 现在我正在使用the java client并且一切正常。
所有信息都在Google Maps page
中