您的位置:首页 > 大数据 > 人工智能

socket(http或者其他网络请求)在主线程中使用会报错:NetworkOnMainThreadException

2016-05-31 11:27 603 查看
在mainActivity中使用socket连接,抛出以下异常

android.os.NetworkOnMainThreadException

            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)

            at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)

            at libcore.io.IoBridge.connectErrno(IoBridge.java:127)

            at libcore.io.IoBridge.connect(IoBridge.java:112)

            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)

            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)

            at java.net.Socket.startupSocket(Socket.java:567)

            at java.net.Socket.tryAllAddresses(Socket.java:128)

            at java.net.Socket.<init>(Socket.java:178)

            at java.net.Socket.<init>(Socket.java:150)

            at panda.com.networkdemo.MainActivity$2.onClick(MainActivity.java:59)

            at android.view.View.performClick(View.java:4438)

            at android.view.View$PerformClick.run(View.java:18422)

            at android.os.Handler.handleCallback(Handler.java:733)

            at android.os.Handler.dispatchMessage(Handler.java:95)

            at android.os.Looper.loop(Looper.java:136)

            at android.app.ActivityThread.main(ActivityThread.java:5001)

            at java.lang.reflect.Method.invokeNative(Native Method)

            at java.lang.reflect.Method.invoke(Method.java:515)

            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)

            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)

            at dalvik.system.NativeStart.main(Native Method)


查看官方API文档:以下解释


Class Overview

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing
for Responsiveness.

Also see 
StrictMode
.

意思大概就是说一个APP如果在主线程中请求网络操作,将会抛出此异常。Android这个设计是为了防止网络请求时间过长而导致界面假死的情况发生。主线程不建议有耗时的操作,例如http请求、较复杂的算法等,否则很容易会出现ARN

解决方法:在activity当中启用多线程进行处理。子线程处理完毕之后再通知主线程进行UI更新
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: