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

来源:互联网 发布:苏州银行业数据统计 编辑:程序博客网 时间:2024/06/06 20:57
在mainActivity中使用socket连接,抛出以下异常
  1. android.os.NetworkOnMainThreadException
  2.             at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
  3.             at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
  4.             at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
  5.             at libcore.io.IoBridge.connect(IoBridge.java:112)
  6.             at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
  7.             at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
  8.             at java.net.Socket.startupSocket(Socket.java:567)
  9.             at java.net.Socket.tryAllAddresses(Socket.java:128)
  10.             at java.net.Socket.<init>(Socket.java:178)
  11.             at java.net.Socket.<init>(Socket.java:150)
  12.             at panda.com.networkdemo.MainActivity$2.onClick(MainActivity.java:59)
  13.             at android.view.View.performClick(View.java:4438)
  14.             at android.view.View$PerformClick.run(View.java:18422)
  15.             at android.os.Handler.handleCallback(Handler.java:733)
  16.             at android.os.Handler.dispatchMessage(Handler.java:95)
  17.             at android.os.Looper.loop(Looper.java:136)
  18.             at android.app.ActivityThread.main(ActivityThread.java:5001)
  19.             at java.lang.reflect.Method.invokeNative(Native Method)
  20.             at java.lang.reflect.Method.invoke(Method.java:515)
  21.             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
  22.             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
  23.             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更新

0 0
原创粉丝点击