Android 3.0 访问WebService 出现 android.os.NetworkOnMainThreadException异常
- 博客分类:
- Android
以前用2.2 访问WebService没有问题,到3.0上访问出现android.os.NetworkOnMainThreadException
找了资料经过实践,解决方法是在activity类中的onCreate方法中添加strict代码,如下:
- public void 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()
- .penaltyLog()
- .penaltyDeath()
- .build());
- ......
- }
public void 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()
.penaltyLog()
.penaltyDeath()
.build());
......
}
似乎是3.0在网络上做了更加严格的限制,更多的查询API上的StrictMode 。。。。
本文探讨了在Android 3.0版本中遇到的网络请求在主线程中运行导致的异常问题,并提供了解决方案。通过在Activity的onCreate方法中设置StrictMode策略,可以避免该类错误的发生。




被折叠的 条评论
为什么被折叠?



