android.os.NetworkOnMainThreadException问题

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

经查证是因为下载的例程

 class TxtDownloadListener implements OnClickListener{
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			String str = httpDownload.downText("http://192.168.1.102/androidServer/a.jsp");
			System.out.println(str);
		}
    	
    }

直接在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版本以上就会出这种异常

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

class TxtDownloadListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			new Thread(txtrun).start();
		}
    	
    }
    
    Runnable txtrun = new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			String str = httpDownload.downText("http://192.168.1.102/androidServer/a.jsp");
			System.out.println(str);
		}
	};

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

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值