android.os.NetworkOnMainThreadException问题

来源:互联网 发布:淘宝客服离开自动回复 编辑:程序博客网 时间:2024/06/09 19:28

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

经查证是因为下载的例程

 class TxtDownloadListener implements OnClickListener{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubString 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{@Overridepublic void onClick(View v) {// TODO Auto-generated method stubnew Thread(txtrun).start();}        }        Runnable txtrun = new Runnable() {@Overridepublic void run() {// TODO Auto-generated method stubString str = httpDownload.downText("http://192.168.1.102/androidServer/a.jsp");System.out.println(str);}};

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

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




原创粉丝点击