我正在构建一个应用程序,但在AsyncTask中出现了NetworkOnMainThreadException异常。
调用:
new POST(this).execute("");
异步任务:
public class POST extends AsyncTask<String, Integer, HttpResponse>{
private MainActivity form;
public POST(MainActivity form){
this.form = form;
}
@Override
protected HttpResponse doInBackground(String... params) {
try {
HttpPost httppost = new HttpPost("http://diarwe.com:8080/account/login");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("email",((EditText)form.findViewById(R.id.in_email)).getText().toString()));
//add more...
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
return new DefaultHttpClient().execute(httppost);
} catch (Exception e) {
Log.e("BackgroundError", e.toString());
}
return null;
}
@Override
protected void onPostExecute(HttpResponse result) {
super.onPostExecute(result);
try {
Gson gSon = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create();
gSon.fromJson(IOUtils.toString(result.getEntity().getContent()), LogonInfo.class).fill(form);
} catch (Exception e) {
Log.e("BackgroundError", e.toString());
}
}
}
日志记录器:
BackgroundError | android.os.NetworkOnMainThreadException
我很困惑为什么在AsyncTask的doInBackground中会抛出这个异常,你有什么想法吗?
AsyncTask
中的所有内容都在主 UI 线程上,除了doInBackground()
。一般的想法是支持以下常见用例:在onPreExecute()
中设置您的ProgressBar
,在onProgressUpdate()
中更新您的ProgressBar
,最后在onPostExecute()
中关闭您的ProgressBar
。所有这些函数都是 UI 线程安全的,而doInBackground()
可以安全地花费尽可能多的时间。 - David Manpearl