nay*_*asu 23 performance android
我试图通过从MainActivity启动IntentService来获取用户的位置.在服务内部我尝试反转地理编码try块内的位置,但是当我捕获异常并打印它时说"超时等待服务器响应"异常.但有几次我有位置.所以我认为没有什么我的代码有问题.但如果它从10中抛出异常8次就没用了.所以你可以建议一些事情来避免这种情况.
http://maps.googleapis.com/maps/api/geocode/json?latlng=lat,lng&sensor=true
Geocoder有超时等待服务器响应的错误.换句话说,您可以从代码中获取此请求以获取相应lat,lng的位置地址的json响应.
小智 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;
}
Run Code Online (Sandbox Code Playgroud)
现在只需更换
geocoder.getFromLocation(locationAddress, 1);
Run Code Online (Sandbox Code Playgroud)
和
getAddrByWeb(getLocationInfo(locationAddress));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
16411 次 |
| 最近记录: |