2 slaks SLaks 于 2013.08.09 16:33 提问

从activity中下载文件的错误

我使用http连接从web站点下载一个图像,如果下载是在服务器中执行就没有问题,如果我在一个activity中使用相同的方法下载文件就有下面的错误:

08-08 13:27:36.800: W/System.err(8010): android.os.NetworkOnMainThreadException
08-08 13:27:36.800: W/System.err(8010):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
08-08 13:27:36.800: W/System.err(8010):     at java.net.InetAddress.lookupHostByName(InetAddress.java:477)
08-08 13:27:36.800: W/System.err(8010):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:277)
08-08 13:27:36.800: W/System.err(8010):     at java.net.InetAddress.getAllByName(InetAddress.java:249)
08-08 13:27:36.800: W/System.err(8010):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:69)
08-08 13:27:36.800: W/System.err(8010):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>(HttpConnection.java:48)
08-08 13:27:36.800: W/System.err(8010):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect(HttpConnection.java:304)
08-08 13:27:36.800: W/System.err(8010):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get(HttpConnectionPool.java:89)
08-08 13:27:36.800: W/System.err(8010):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpConnection(HttpURLConnectionImpl.java:292)
08-08 13:27:36.800: W/System.err(8010):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConnection(HttpURLConnectionImpl.java:274)
08-08 13:27:36.800: W/System.err(8010):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.retrieveResponse(HttpURLConnectionImpl.java:1038)
08-08 13:27:36.800: W/System.err(8010):     at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHeaderField(HttpURLConnectionImpl.java:481)
08-08 13:27:36.800: W/System.err(8010):     at java.net.URLConnection.getHeaderFieldInt(URLConnection.java:572)
08-08 13:27:36.800: W/System.err(8010):     at java.net.URLConnection.getContentLength(URLConnection.java:335)

我用的下面的方法调用下载方法:

new Thread(new Runnable() {
        public void run() {
             downloadFile(imagePath);
                }
              }).start();

1个回答

Jave_
Jave_   2013.08.09 16:50

运行在主线程里了,用:

new Thread(){
    @Override
    public void run(){
        //你要执行的方法
        //执行完毕后给handler发送一个空消息
        handler.sendEmptyMessage(0);
    }
}.start();


//定义Handler对象
private Handler handler =new Handler(){
    @Override
    //当有消息发送出来的时候就执行Handler的这个方法
    public void handleMessage(Message msg){
    super.handleMessage(msg);
    //处理UI
    }
};
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!