我正在尝试通过启动 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);
}
添加此代码将不再为您提供主线程异常上的网络。
您必须在线程中可运行的 run() 函数上执行实际的网络 IO。您不只是创建一个线程然后执行 IO。