`
qiang106
  • 浏览: 383862 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

关于android.os.NetworkOnMainThreadException异常

 
阅读更多

在开发使用网络连接的android应用时,遇到这么一个问题,只要一连接网络就报下面这个异常

 

android.os.NetworkOnMainThreadException

异常截图

查了下API和源码,发现原来在4.0之后,使用网络时都会用到

 

StrictMode

中 AndroidBlockGuardPolicy的检查策略,如果在UI线程连接网络就会报这个异常,尝试了一下把AndroidMainfest中android:targetSdkVersion="15"去掉或者更换成更低的版本,这个异常就不会报了。最根本的解决办法是把这些网络操作放到非UI线程去执行。

 

在API文档中这一点也有了说明,这样也好,避免我们把耗时的网络操作放到UI线程中去执行,提高应用的用户体验。


在此记一下,免得以后忘记,也分享出来,希望朋友们不会再范同样的错误了。

 

 

API说明贴出来:

 

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. 

 

 

  • 大小: 89.9 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics