geocoder.getFromLocation函数抛出“超时等待服务器响应”异常

时间:2014-05-13 17:37:50

标签: android performance

我试图通过从MainActivity启动IntentService来获取用户的位置。在服务内部我尝试反转地理编码try块内的位置,但是当我捕获异常并打印它时说“超时等待服务器响应”异常。但是有几次我有位置。所以我认为没有什么我的代码有问题。但是如果它从10中抛出8次异常就没用了。所以你可以建议一些事情来避免这种情况。

4 个答案:

答案 0 :(得分:5)

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

Geocoder有超时等待服务器响应的错误。除此之外,您可以从代码中获取此请求以获取相应lat,lng的位置地址的json响应。

答案 1 :(得分:1)

由于无法使用互联网连接,我受到了影响,并且出现了错误。

请检查是否已分配互联网权限:

 <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);
            }
        }
    }

希望它会有所帮助。

答案 2 :(得分:1)

以下是快速解决方案。

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;
        }
    }
}

答案 3 :(得分:0)

这是一个简单而有效的解决方案:

创建以下两个函数:

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));