我尝试将图像文件从Android发送到另一台计算机,但我收到错误:android.os.NetworkOnMainThreadException
03-08 00:57:40.474: E/AndroidRuntime(1201): FATAL EXCEPTION: main
03-08 00:57:40.474: E/AndroidRuntime(1201): Process: com.example.singh, PID: 1201
03-08 00:57:40.474: E/AndroidRuntime(1201): android.os.NetworkOnMainThreadException
03-08 00:57:40.474: E/AndroidRuntime(1201): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
03-08 00:57:40.474: E/AndroidRuntime(1201): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
03-08 00:57:40.474: E/AndroidRuntime(1201): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
03-08 00:57:40.474: E/AndroidRuntime(1201): at libcore.io.IoBridge.connect(IoBridge.java:112)
03-08 00:57:40.474: E/AndroidRuntime(1201): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
03-08 00:57:40.474: E/AndroidRuntime(1201): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
03-08 00:57:40.474: E/AndroidRuntime(1201): at java.net.Socket.startupSocket(Socket.java:567)
03-08 00:57:40.474: E/AndroidRuntime(1201): at java.net.Socket.tryAllAddresses(Socket.java:128)
03-08 00:57:40.474: E/AndroidRuntime(1201): at java.net.Socket.<init>(Socket.java:178)
03-08 00:57:40.474: E/AndroidRuntime(1201): at java.net.Socket.<init>(Socket.java:150)
03-08 00:57:40.474: E/AndroidRuntime(1201): at com.example.singh.MainActivity$2.onClick(MainActivity.java:65)
03-08 00:57:40.474: E/AndroidRuntime(1201): at android.view.View.performClick(View.java:4438)
03-08 00:57:40.474: E/AndroidRuntime(1201): at android.view.View$PerformClick.run(View.java:18422)
03-08 00:57:40.474: E/AndroidRuntime(1201): at android.os.Handler.handleCallback(Handler.java:733)
03-08 00:57:40.474: E/AndroidRuntime(1201): at android.os.Handler.dispatchMessage(Handler.java:95)
03-08 00:57:40.474: E/AndroidRuntime(1201): at android.os.Looper.loop(Looper.java:136)
03-08 00:57:40.474: E/AndroidRuntime(1201): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-08 00:57:40.474: E/AndroidRuntime(1201): at java.lang.reflect.Method.invokeNative(Native Method)
03-08 00:57:40.474: E/AndroidRuntime(1201): at java.lang.reflect.Method.invoke(Method.java:515)
03-08 00:57:40.474: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-08 00:57:40.474: E/AndroidRuntime(1201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-08 00:57:40.474: E/AndroidRuntime(1201): at dalvik.system.NativeStart.main(Native Method)
03-08 00:57:42.944: I/Process(1201): Sending signal. PID: 1201 SIG: 9
答案 0 :(得分:1)
您正尝试在主线程上发送/上传图片。你应该在后台线程中做到这一点。您可以使用AsyncTask来实现此目的。
Android文档:
应用程序尝试执行时抛出的异常 在其主线程上进行网络操作。
这仅适用于针对Honeycomb SDK或。的应用程序 更高。允许使用早期SDK版本的应用程序 他们的主要事件循环线程上的网络,但它很重要 泄气。请参阅文档Designing for Responsiveness。