gpt4 book ai didi

java - 如何使用另一个线程来停止 NetworkOnMainThreadException?

转载 作者:行者123 更新时间:2023-11-29 05:41:59 27 4
gpt4 key购买 nike

我正在尝试通过启动 TCP 服务器来访问 android 网络。但是当我创建一个新线程时,要么 Thread t = new Thread(runnable);
t.start();

FutureTask我仍然得到networkonmainthreadexception...

最佳答案

使用 AsyncTask 执行网络相关操作

例如:

private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
for (String url : urls) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();

BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}

} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}

@Override
protected void onPostExecute(String result) {
textView.setText(result);
}
}

或者你可以这样做,虽然不推荐

    if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy =
new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

添加这段代码不会再给你网络上的主线程异常了。

关于java - 如何使用另一个线程来停止 NetworkOnMainThreadException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17127001/

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