NetworkOnMainThreadException与AsyncTask [英] NetworkOnMainThreadException with AsyncTask
问题描述
我需要从我的Android应用发出一些HTTP请求. 我根据需要使用AsyncTask,并将网络部分放在doInBackground中.
I need to do some HTTP requests from my android app. I use AsyncTask as needed, with the network part in doInBackground.
这是我的请求类别:
public class AsyncRequest extends AsyncTask<Void, Integer, HttpResponse>{
private ProgressDialog dialog;
private Activity activity;
private HttpUriRequest query;
private HttpClient client;
private HttpResponse response;
private String dialogMsg;
private String uri;
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public AsyncRequest(Activity a, HttpUriRequest q, HttpClient c, String m) {
query = q;
client = c;
activity = a;
dialog = new ProgressDialog(a);
dialogMsg = m;
}
@Override
protected void onPostExecute(HttpResponse res) {
if (dialog.isShowing())
dialog.dismiss();
}
protected void onPreExecute() {
this.dialog.setMessage(dialogMsg);
this.dialog.show();
}
@Override
protected HttpResponse doInBackground(Void... arg0) {
try {
response = client.execute(query);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
protected HttpResponse getResponse() {
return response;
}
}
而且,在我的UI线程中,我是这样使用的:
And, in my UI thread, I use it this way :
AsyncRequest request;
HttpClient httpClient = new DefaultHttpClient();
HttpGet getQuery = new HttpGet("Here goes my url");
HttpResponse response = null;
String rt = "Null";
getQuery.setHeader("Authorization", getIntent().getExtras().getString("token"));
request = new AsyncRequest(this, getQuery, httpClient, "Loading events...");
try {
response = request.execute().get(3, TimeUnit.SECONDS);
} catch (Exception e) {
e.printStackTrace();
}
HttpEntity entity = response.getEntity();
try {
rt = EntityUtils.toString(entity);
} catch (Exception e) {
e.printStackTrace();
return ;
}
所以,我是一名Android初学者,但是我猜想在与网络相关的代码在主线程中执行时会捕获此异常.但是我在doInBackground()方法中运行client.execute().是对execute().get()的调用(在ui线程中)导致此问题吗?
So, I'm an android beginner, but I guess this exception is caught when network related code is executed in main thread. But I run client.execute() in my doInBackground() method. Is it the call to execute().get() (in ui thread) that causes the problem ?
推荐答案
您有这个
response = request.execute().get(3, TimeUnit.SECONDS);
调用get()
使AsyncTask
不再是异步的.它阻止ui线程等待响应.这导致NetworkOnMainThreadException
.
Calling get()
makes AsyncTask
no more Asynchronous. It blocks the ui thread waiting for the response. This leads to NetworkOnMainThreadException
.
摆脱get(3, TimeUnit.SECONDS);
只需使用request.execute()
.您可以在onPostExecute
中更新ui.您也可以将interface用作Activity的回调.
Just use request.execute()
. You can update ui in onPostExecute
. You can also use interface as a callback to the Activity.
在下面的链接中通过blackbelt检查答案
Check the answer by blackbelt in the below link
这篇关于NetworkOnMainThreadException与AsyncTask的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!