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

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

     真是问题不断,在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