Geocoder.getFromLocation() 没有 return 任何地址

Geocoder.getFromLocation() does not return any addresses

我正在尝试通过经度和纬度来获取位置信息(国家名称、城市名称等)。但是,下面的代码没有 return 任何地址,addresses.size() 总是零!!我需要帮助。谢谢。

public class FirstUsage extends Activity{

private LocationListener myLocListener;
private LocationManager myLocManager;
private TextView tv;
private Button okButt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.first_use_page);

    tv = (TextView)findViewById(R.id.TextView_firstPageCoordination);
    okButt = (Button)findViewById(R.id.firstPageOKButt);

    myLocManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    setLocationChangeListener();
}

private void setLocationChangeListener() {
    myLocListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

            /*----------to get City-Name from coordinates ------------- */
            String countryName = null;
            Geocoder gcd = new Geocoder(FirstUsage.this, Locale.getDefault());
            List<Address> addresses;
            try {
                addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
                if (addresses.size() > 0) {

                    Address returnedAddress = addresses.get(0);
                    countryName = returnedAddress.getCountryName();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            tv.setText("Your current country is: " + countryName + "\n Your current coordination is:\n" + "Longitude: " + location.getLongitude() + "   Latitude: " + location.getLatitude());


            /////
            if (ActivityCompat.checkSelfPermission(FirstUsage.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(FirstUsage.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            myLocManager.removeUpdates(myLocListener);
        }

它有时会在连接不可用或后端未实现时附加。验证这两件事的最好方法是使用以下方法检查地理编码器是否存在:

gcd.isPresent ()

Returns true if the Geocoder methods getFromLocation and getFromLocationName are implemented. Lack of network connectivity may still cause these methods to return null or empty lists.

来自android documentation

The Geocoder class requires a backend service that is not included in the core android framework.

问题是 Geocoder 后端服务在您的 device/simulator 中不可用。您的 device/simulator 需要 Google API 才能正确使用 Grocoder。