我正在尝试获取当前位置并获取前往某个目的地的行车路线。
我能够获取我的位置,当我执行行车路线代码时,我在以下行中得到 android.os.NetworkOnMainThreadException
HttpResponse response = httpClient.execute(httpPost, localContext);
响应为 NULL。我该怎么办 ?
public Document getDocument(LatLng start, LatLng end, String mode) {
String url = "http://maps.googleapis.com/maps/api/directions/xml?"
+ "origin=" + start.latitude + "," + start.longitude
+ "&destination=" + end.latitude + "," + end.longitude
+ "&sensor=false&units=metric&mode="+mode;
try {
new DownloadWebpageTask().execute(url);
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(url);
HttpResponse response = httpClient.execute(httpPost, localContext);
InputStream in = response.getEntity().getContent();
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(in);
return doc;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
As NetworkOnMainThreadException
状态,网络请求只能在后台线程中执行。你不能在主线程中执行。
创建一个AsycTask
并执行你的代码doInBackground()
方法。后台操作完成后,您可以在中更新UIonPostExecute
new AsyncTask<Void, Integer, Document>(){
@Override
protected Document doInBackground(Void... params) {
try {
// call you method here
return getDocument();
} catch (Exception ex) {
// handle the exception here
}
return null;
}
@Override
protected void onPostExecute(Document result){
// update the UI with your data
}
}.execute();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)