Подтвердить что ты не робот

Функция geocoder.getFromLocation выбрала исключение "Задержка ожидания ответа сервера"

Я пытаюсь получить местоположение пользователя, запустив IntentService из MainActivity. Внутри службы я пытаюсь отменить геокодирование местоположения внутри блока try, но когда я поймаю исключение и распечатаю его, вы получите сообщение об ошибке "Отложенное время ожидания ответа сервера". Но несколько раз у меня есть location.so я думаю, что нет ничего неправильно с моим кодом. Но это не будет полезно, если он выдает исключение 8 раз из 10. Так вы можете предложить кое-что, чтобы этого избежать.

4b9b3361

Ответ 1

http://maps.googleapis.com/maps/api/geocode/json?latlng=lat,lng&sensor=true

Геокодер, имеющий ошибку таймаута, ожидающую ответа сервера. В дополнение к этому вы можете удалить этот запрос из своего кода, чтобы получить ответ json адреса местоположения соответствующих lat, lng.

Ответ 2

Я пострадал и получил ошибку из-за недоступности подключения к Интернету.

Пожалуйста, проверьте, разрешено ли разрешение на доступ в Интернет:

 <uses-permission android:name="android.permission.INTERNET" />

И дважды проверьте, что ваш Интернет включен или нет.

И ради получения ответа я пишу свой код в AsyncTask, как показано ниже:

 class GeocodeAsyncTask extends AsyncTask<Void, Void, Address> {

        String errorMessage = "";

        @Override
        protected void onPreExecute() {

            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected Address doInBackground(Void ... none) {
            Geocoder geocoder = new Geocoder(DashboardActivity.this, Locale.getDefault());
            List<Address> addresses = null;


            double latitude = Double.parseDouble(strLatitude);
            double longitude = Double.parseDouble(strLongitude);

            try {
                addresses = geocoder.getFromLocation(latitude, longitude, 1);
            } catch (IOException ioException) {
                errorMessage = "Service Not Available";
                Log.e(TAG, errorMessage, ioException);
            } catch (IllegalArgumentException illegalArgumentException) {
                errorMessage = "Invalid Latitude or Longitude Used";
                Log.e(TAG, errorMessage + ". " +
                        "Latitude = " + latitude + ", Longitude = " +
                        longitude, illegalArgumentException);
            }


            if(addresses != null && addresses.size() > 0)
                return addresses.get(0);

            return null;
        }

        protected void onPostExecute(Address address) {
            if(address == null) {
                progressBar.setVisibility(View.INVISIBLE);

                tvcurrentLOc.setText(errorMessage);
            }
            else {
                String addressName = "";
                for(int i = 0; i < address.getMaxAddressLineIndex(); i++) {
                    addressName += "," + address.getAddressLine(i);
                }
                progressBar.setVisibility(View.INVISIBLE);

                tvcurrentLOc.setText(addressName);
            }
        }
    }

Надеюсь, это поможет.

Ответ 3

Вот это быстрое решение для этого.

public class GPSL extends Service implements LocationListener {
public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    try
                    {
                        locationManager.requestLocationUpdates(
                                LocationManager.NETWORK_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("Network", "Network");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                    catch (SecurityException e)
                    {
                        e.printStackTrace();
                    }

                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        try
                        {
                            locationManager.requestLocationUpdates(
                                    LocationManager.GPS_PROVIDER,
                                    MIN_TIME_BW_UPDATES,
                                    MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                            Log.d("GPS Enabled", "GPS Enabled");
                            if (locationManager != null) {
                                location = locationManager
                                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                                if (location != null) {
                                    latitude = location.getLatitude();
                                    longitude = location.getLongitude();
                                }
                            }
                        }
                        catch (SecurityException e)
                        {
                            e.printStackTrace();
                        }

                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }

public List<Address> getGeocoderAddress(Context context) {
        if (location != null) {

            Geocoder geocoder = new Geocoder(context, Locale.ENGLISH);

            try {
                /**
                 * Geocoder.getFromLocation - Returns an array of Addresses
                 * that are known to describe the area immediately surrounding the given latitude and longitude.
                 */
                List<Address> addresses = geocoder.getFromLocation(latitude, longitude, this.geocoderMaxResults);

                return addresses;
            } catch (IOException e) {
                //e.printStackTrace();
                Log.e("Gecoder", "Impossible to connect to Geocoder", e);
            }
        }

        return null;
    }

    /**
     * Try to get AddressLine
     * @return null or addressLine
     */
    public String getAddressLine(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String addressLine = address.getAddressLine(0);

            return addressLine;
        } else {
            return null;
        }
    }

    /**
     * Try to get Locality
     * @return null or locality
     */
    public String getLocality(Context context) {
        List<Address> addresses = getGeocoderAddress(context);

        if (addresses != null && addresses.size() > 0) {
            Address address = addresses.get(0);
            String locality = address.getLocality();

            return locality;
        }
        else {
            return null;
        }
    }
}

Ответ 4

Вот простое и эффективное решение:

Создайте следующие две функции:

public static JSONObject getLocationInfo(String address) {
    StringBuilder stringBuilder = new StringBuilder();
    try {

    address = address.replaceAll(" ","%20");    

    HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    stringBuilder = new StringBuilder();


        response = client.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return jsonObject;
}
private static List<Address> getAddrByWeb(JSONObject jsonObject){
    List<Address> res = new ArrayList<Address>();
    try
    {
        JSONArray array = (JSONArray) jsonObject.get("results");
        for (int i = 0; i < array.length(); i++)
        {
            Double lon = new Double(0);
            Double lat = new Double(0);
            String name = "";
            try
            {
                lon = array.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng");

                lat = array.getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
                name = array.getJSONObject(i).getString("formatted_address");
                Address addr = new Address(Locale.getDefault());
                addr.setLatitude(lat);
                addr.setLongitude(lon);
                addr.setAddressLine(0, name != null ? name : "");
                res.add(addr);
            }
            catch (JSONException e)
            {
                e.printStackTrace();

            }
        }
    }
    catch (JSONException e)
    {
        e.printStackTrace();

    }

    return res;
}

Теперь просто замените

geocoder.getFromLocation(locationAddress, 1); 

с

getAddrByWeb(getLocationInfo(locationAddress));