android.os.NetworkOnMainThreadException

android.os.NetworkOnMainThreadException

一、出现原因

我把网络读取数据的操作写进了主线程

看名字就应该知道,是网络请求在MainThread中产生的异常 

二、产生原因

官网解释

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.

https://developer.android.com/intl/zh-cn/reference/android/os/NetworkOnMainThreadException.html

解释一下,从Honeycomb SDK(3.0)开始,google不再允许网络请求(HTTP、Socket)等相关操作直接在Main Thread类中,其实本来就不应该这样做,直接在UI线程进行网络操作,会阻塞UI、用户体验相当bad!即便google不禁止,一般情况下我们也不会这么做吧~

所以,也就是说,在Honeycomb SDK(3.0)以下的版本,你还可以继续在Main Thread里这样做,在3.0以上,就不行了,建议

二、解决方法

直接在main Thread 进行网络操作的方法

在发起Http请求的Activity里面的onCreate函数里面添加如下代码:

1 StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
2                 .detectDiskReads().detectDiskWrites().detectNetwork()
3                 .penaltyLog().build());
4         StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
5                 .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
6                 .penaltyLog().penaltyDeath().build());

 这种方法简单好用

详细参考:http://blog.csdn.net/mad1989/article/details/25964495

原文地址:https://www.cnblogs.com/Renyi-Fan/p/7301116.html