最近在做一个项目,涉及到网络通信这块,需要向服务器发送请求,获取服务器端的数据,程序在android 2.2系统中运行正常,在4.0系统中运行获取不到数据。
网上查了下资料,发现 Android在4.0之前的版本 支持在主线程中访问网络,但是在4.0以后对这部分程序进行了优化,访问网络的代码不能写在主线程中了。
解决方法如下:
在OnCreate()中加入如下代码:
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());</span>
问题就解决了,StrictMode方法仅在4.0系统中使用,因此需使用4.0以上的系统。