在Activity中启动一个网络连接遇到android.os.NetworkOnMainThreadException

来源:互联网 发布:网上兼职淘宝刷好评 编辑:程序博客网 时间:2024/06/07 11:33

     真是问题不断,在Android3.1平台上开发时,通过自定义Application类,在其中的onCreate方法中初始化了一个网络连接,可恶的是发生了android.os.NetworkOnMainThreadException的错误。

     借助网络的力量,得知在3.0平台上由于对网络的限制比较严格,无法之间初期。不得不在网络初期之前加了一段代码。

         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());     super.onCreate();     //.....初始化网络连接

 

详细说明,参考http://android.yyable.com/reference/android/os/StrictMode.html

 

0 0
原创粉丝点击