码迷,mamicode.com
首页 > 移动开发 > 详细

android.os.NetworkOnMainThreadException 异常处理

时间:2016-07-10 23:21:15      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:

当我试图在UI线程(MainActivity)连接网络的时候,运行时抛出异常droid.os.NetworkOnMainThreadException 

安卓的官方文档说

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.

基于减少UI线程耗时操作的考虑,安卓3.0以上不再允许在UI线程上进行网络连接。

解决方法

1.使用Strict Mode 强行在UI线程连接,(官方不推荐)

2.开一个线程进行网络连接,再用Handler将结果传给UI线程。 

 

android.os.NetworkOnMainThreadException 异常处理

标签:

原文地址:http://www.cnblogs.com/yidan621/p/5658640.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!