地理coder.getFromLocation函数抛出"超时等待服务器响应"例外 [英] geocoder.getFromLocation function throws "Timed out waiting for server response" exception
问题描述
我想从MainActivity开始IntentService来获得用户的位置。里面的服务,我设法扭转地理$ C C A try块内的位置$但是当我捕获该异常并打印它说:超时等待服务器响应exception.But几次,我已经拿到了location.so我觉得有什么错我的code.But如果抛出异常8超时10.So,你可以建议一些事情,以避免这种情况就不会是有益的。
I am trying to get location of user by starting IntentService from MainActivity. Inside the service i try to reverse geocode the location inside a try block but when i catch the exception and print it says "Timed out waiting for server response" exception.But a few times I have got the location.so i think there is nothing wrong with my code.But it won't be useful if it throws exception 8 times out of 10.So can you suggest some thing to avoid this.
推荐答案
下面是一个简单的工作液:
Here is a simple and working solution:
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));
这篇关于地理coder.getFromLocation函数抛出&QUOT;超时等待服务器响应&QUOT;例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!