android.os.NetworkOnMainThreadException问题

来源:互联网 发布:h3c dhcp mac地址绑定 编辑:程序博客网 时间:2024/05/18 23:24

原文地址:http://blog.csdn.net/davidtps/article/details/7057775

 

 

原先的下载程序在2.3.3可以正常运行但是在android4.0运行时报出如上错误

经查证是因为下载的例程

[java] view plaincopyprint?
  1. class TxtDownloadListener implements OnClickListener{  
  2.     @Override  
  3.     public void onClick(View v) {  
  4.         // TODO Auto-generated method stub  
  5.         String str = httpDownload.downText("http://192.168.1.102/androidServer/a.jsp");  
  6.         System.out.println(str);  
  7.     }  
  8.       
  9.    }  


直接在UI主进程中运行,如文档中介绍

Class Overview

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged.

在3.0版本以上就会出这种异常

将下载文件的代码放到线程中去就不会报错

[java] view plaincopyprint?
  1. class TxtDownloadListener implements OnClickListener{  
  2.   
  3.         @Override  
  4.         public void onClick(View v) {  
  5.             // TODO Auto-generated method stub  
  6.             new Thread(txtrun).start();  
  7.         }  
  8.           
  9.     }  
  10.       
  11.     Runnable txtrun = new Runnable() {  
  12.           
  13.         @Override  
  14.         public void run() {  
  15.             // TODO Auto-generated method stub  
  16.             String str = httpDownload.downText("http://192.168.1.102/androidServer/a.jsp");  
  17.             System.out.println(str);  
  18.         }  
  19.     };  


我是用Thread实现的线程启动可以有别的方法

链接:http://www.vogella.de/articles/AndroidPerformance/article.html