Android “NetworkOnMainThreadException”出错原因及解决办法

原因: 不允许在主线程中通讯

方法1:非要在主线程中,当然也可以,这样去处理:

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());

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());

这样就不用放在一个线程中执行。
方法2:

new Thread(){
   @Override
   public void run()
   {
     //网络访问
   }
}.start();

 

posted @ 2014-12-08 16:29  jiduoduo  阅读(533)  评论(0编辑  收藏  举报