此错误仅在模拟器上发生,但完全在移动设备上运行...
错误
07-30 05:38:09.024: E/AndroidRuntime(941): android.os.NetworkOnMainThreadException
07-30 05:38:09.024: E/AndroidRuntime(941): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
07-30 05:38:09.024: E/AndroidRuntime(941): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
07-30 05:38:09.024: E/AndroidRuntime(941): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
07-30 05:38:09.024: E/AndroidRuntime(941): at libcore.io.IoBridge.connect(IoBridge.java:112)
07-30 05:38:09.024: E/AndroidRuntime(941): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
07-30 05:38:09.024: E/AndroidRuntime(941): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
07-30 05:38:09.024: E/AndroidRuntime(941): at java.net.Socket.connect(Socket.java:842)
07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-30 05:38:09.024: E/AndroidRuntime(941): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
答案 0 :(得分:1)
此错误是因为主线程上的网络相关操作,来自android ICS版本的网络相关代码应该在AsyncTask ..
private class MyTask extends AsyncTask<Void , Void, Void > {
private Exception exception;
protected Void doInBackground(Void... urls) {
// your code here
}
protected void onPostExecute(Void feed) {
}
}
像这样调用asynctask
MyTask task = new MyTask ();
task.execute();
答案 1 :(得分:1)
您无法在Honeycombe上的UI线程上执行网络IO。从技术上讲,它可以在早期版本的Android上运行,但这是一个非常糟糕的主意,因为它会导致您的应用停止响应,并可能导致操作系统因为表现不佳而导致您的应用被杀。您需要运行后台进程或使用AsyncTask在后台线程上执行网络事务。
但是如果你想强迫你做app,那么请使用下面的代码,
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
但同样不建议使用它。 请阅读此link以获取更多信息。