6

当我在模拟器上测试时,它可以工作,但是当我用我的设备(galaxy s3)测试时,它在以下代码期间不断抛出错误:

HttpResponse response;
        response = httpclient.execute(httppost);

例外情况:

09-03 08:16:49.018: E/AndroidRuntime(24254): java.lang.RuntimeException: Unable to start activity ComponentInfo{sg.dianping/sg.dianping.activity.ItemListActivity}: android.os.NetworkOnMainThreadException
09-03 08:16:49.018: E/AndroidRuntime(24254):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at android.app.ActivityThread.access$600(ActivityThread.java:128)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at android.os.Handler.dispatchMessage(Handler.java:99)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at android.os.Looper.loop(Looper.java:137)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at android.app.ActivityThread.main(ActivityThread.java:4517)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at java.lang.reflect.Method.invokeNative(Native Method)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at java.lang.reflect.Method.invoke(Method.java:511)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at dalvik.system.NativeStart.main(Native Method)
09-03 08:16:49.018: E/AndroidRuntime(24254): Caused by: android.os.NetworkOnMainThreadException
09-03 08:16:49.018: E/AndroidRuntime(24254):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
09-03 08:16:49.018: E/AndroidRuntime(24254):    at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
4

1 回答 1

15

NetworkingOnMainThread当您在 UI 线程上执行网络活动时,将引发此异常。它有可能阻塞主线程,因为它会等到网络连接完成后再恢复,从而阻塞线程。

您有 2 个选项。

1 - 将您的所有网络移动到不同的线程。最常见和最简单的解决方案是AsyncTask 但还有其他选项,例如Handlers。这是推荐的选项。

2-您可以更改策略以允许在 UI 线程上联网。

只需添加此代码

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

不推荐使用此选项,因为它只是绕过异常。抛出异常是有原因的。我会选择第一个选项。有很多关于如何实现的教程AsyncTask

祝你好运

于 2012-09-03T00:42:21.267 回答