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

2 篇文章 0 订阅
1 篇文章 0 订阅
在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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值