gpt4 book ai didi

android - 为什么我使用 AsyncTask 时会出现 android.os.NetworkOnMainThreadException?

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:23:49 24 4
gpt4 key购买 nike

我在 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 + "\n");
}
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 stub

return 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 block 并给我 this异常 LogCat
任何建议和想法将不胜感激。
谢谢

最佳答案

您使用了错误的 AsyncTask 方法来放置您的网络相关代码。请将它移动到 doInBackground,因为 onPreExecute 发生在主线程上。于是,异常发生了。详情为here .

关于android - 为什么我使用 AsyncTask 时会出现 android.os.NetworkOnMainThreadException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12153762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com