天下之事常成于困约,而败于奢靡。这篇文章主要讲述为什么我用AsyncTask获取android.os.NetworkOnMainThreadException?相关的知识,希望能为你提供帮助。
我在AsynkTask中编写了网络操作代码时得到了android.os.NetworkOnMainThreadException。抛出这个例外有什么其他原因吗?
这是我的代码:
public class Background_confirmation extends AsyncTask<
Void, Integer, Void>
{
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(Confirmation.this,
"Please wait...", "Retrieving data ...", true);
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://68.121.167.160/sip_chat_api/create_account.php?useralias="
+ useralias + "&
cntname=" + cntcode + "");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
if (backgroung_flag == 1) {} else {
if (is != null) {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "
");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag",
"Error converting result " + e.toString());
}
}}
super.onPreExecute();
}@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stubreturn null;
}@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (progressDialog.isShowing()) {
progressDialog.dismiss();
// progressDialog.setCancelable(true);
}
super.onPostExecute(result);
}}
我在OnCreate()中调用此类
new Background_confirmation().execute();
但它总是在Catch块中,并给我this例外LogCat 任何建议和想法都将得到赞赏。 谢谢
答案
public class Background_confirmation extends AsyncTask<
Void, Integer, String>
{
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = ProgressDialog.show(Confirmation.this, "Please wait...", "Retrieving data ...", true);
}@Override
protected String doInBackground(Void... params) {try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://68.121.167.160/sip_chat_api/create_account.php?useralias=" + useralias + "&
cntname=" + cntcode + "");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
if (backgroung_flag == 1) {} else {
if (is != null) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "
");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
}
}
return result;
}@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
// progressDialog.setCancelable(true);
}
}
}
您的代码应该像上面那样改变。你需要考虑的事情
- 连接应该在
doInBackground()
内编码 - 如果你想得到
doInBackground()
的结果,你必须把它带入onPostExecute()
- 这意味着您必须在
doInBackground()
中返回一个String值,其中AsyncTask
类的第三个参数也应该是String(这不是Wayne的答案)
InputStream
。如果您只使用InputStream
,请确保代码始终到达else部分。另一答案您使用了错误的AsyncTask方法来放置与网络相关的代码。请把它移到
doInBackground
,因为onPreExecute
发生在主线上。所以,发生了异常。详情是here。另一答案【为什么我用AsyncTask获取android.os.NetworkOnMainThreadException()】将所有网络请求代码放在
doInBackground
中。 onPreExecute
和onPostExecute
将在UI线程(主要的thead)上运行,因此如果您在这两种方法上请求网络,您将获得一个例外。public class Background_confirmation extends AsyncTask<
Void, Integer, Void>
{
@Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(Confirmation.this,
"Please wait...", "Retrieving data ...", true);
}@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stubtry {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://68.121.167.160/sip_chat_api/create_account.php?useralias="
+ useralias + "&
cntname=" + cntcode + "");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
e.printStackTrace();
}
if (backgroung_flag == 1) {} else {
if (is != null) {
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "
");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag",
"Error converting result " + e.toString());
}
}}
}@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
if (progressDialog.isShowing()) {
progressDialog.dismiss();
// progressDialog.setCancelable(true);
}}}
推荐阅读
- 如何取消Android中的AsyncTask()
- 在Android中如何从Asynctask接收字符串()
- Android SDK AsyncTask doInBackground未运行(子类)
- Android Media Player(开始调用状态4错误(-38,0))
- Android AsyncTask在完成工作后返回值
- 如何解决MySQL异常SQLSTATE [HY000](常规错误:1364字段”field_name”没有默认值)
- 如何解决(解决方案)Google的”程序员”游戏(海龟级)
- 如何在CentOS中安装bcmath扩展
- 如何使用EventListener根据用户在Symfony 2.8中的角色将用户重定向到特定页面