我正在使用以下代码从本地主机下载图片.它会导致意外错误



当我运行以下代码时

    Runnable r = new Runnable() {
    @Override
    public void run() {
         final String urlString = "http://10.0.2.2/conn/s.png";
            // URL newurl = null;
                     try{   
                do
                {
                            if (ch==1)
                            {
                                //Thread.sleep(7000);
                                HttpGet httpRequest = new HttpGet(new URL(urlString).toURI());
                                HttpClient httpClient = new DefaultHttpClient();
                                HttpResponse response = (HttpResponse) httpClient.execute(httpRequest);
                                HttpEntity entity = response.getEntity();
                                BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity); 
                                    InputStream is = bufHttpEntity.getContent();
                                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                                   im.destroyDrawingCache();
                                    im.setImageBitmap(bitmap);   
                                    bitmap=null;
                                   // Thread.sleep(3000);
                                    out.write(1);
                                   out.flush();


                                 }  
                }
                while(( ch=in.read()) == 1);
                     }
                     catch(IOException ex)
                     {
                     }
                    catch(URISyntaxException ex)
                    {}
    }
};

线程初始化如下:

                  t = new Thread(r);
          t.start();

我得到以下异常:

03-18 01:20:50.399: E/AndroidRuntime(305):  at android.view.ViewRoot.checkThread(ViewRoot.java:2683)
03-18 01:20:50.399: E/AndroidRuntime(305):  at android.view.ViewRoot.requestLayout(ViewRoot.java:557)
03-18 01:20:50.399: E/AndroidRuntime(305):  at android.view.View.requestLayout(View.java:7918)
03-18 01:20:50.399: E/AndroidRuntime(305):  at android.view.View.requestLayout(View.java:7918)
03-18 01:20:50.399: E/AndroidRuntime(305):  at android.view.View.requestLayout(View.java:7918)
03-18 01:20:50.399: E/AndroidRuntime(305):  at android.view.View.requestLayout(View.java:7918)
03-18 01:20:50.399: E/AndroidRuntime(305):  at android.view.View.requestLayout(View.java:7918)
03-18 01:20:50.399: E/AndroidRuntime(305):  at android.widget.ImageView.setImageDrawable(ImageView.java:306)
03-18 01:20:50.399: E/AndroidRuntime(305):  at android.widget.ImageView.setImageBitmap(ImageView.java:320)
03-18 01:20:50.399: E/AndroidRuntime(305):  at remote.presentation.rshare$1.run(rshare.java:124)
03-18 01:20:50.399: E/AndroidRuntime(305):  at java.lang.Thread.run(Thread.java:1096)

您正在从线程更改UI,在Android中无法做到这一点。它必须在UI线程上完成。与使用线程相比,我更喜欢AsyncTasks。此AsyncTask将从url获取图像。

private class GetImage extends AsyncTask<String,Void,Bitmap>{
    private ImageView view;
    public GetImage(ImageView iv){
         this.view = iv;
    }
    protected Bitmap doInBackground(String... params) {
                    //background thread
        try {
            return BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(Bitmap b){
        if(b != null)
            this.view.setImageBitmap(b); 
    }
}

使用

new GetImage(myImageView).execute(someURL);

EDIT(编辑原因,请参阅注释)-以下代码将重复下载与提问者想要的相同的图像

为GetImage类创建一个类变量

GetImage getImageInstance = new GetImage(myImageView); 
getImageInstance.execute(url);

修改类

private class GetImage extends AsyncTask<String,Bitmap,Void>{
    private ImageView view;
    Bitmap bitmap = null;
    long lastUpdateTimestamp = System.currentTimeMillis();
    public GetImage(ImageView iv){
         this.view = iv;
    }
    protected Bitmap doInBackground(String... params) {
                    //background thread
        while(running){
            try {
                //if more than 2 seconds have elapsed update the image
                if((System.currentTimeMillis() - lastUpdateTimestamp) > 2000){
                    bitmap = BitmapFactory.decodeStream((InputStream)new URL(params[0]).getContent());
                    pubilshProgress(bitmap);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                 e.printStackTrace();
            }
        }
        return null;
    }
    //this method that will update the UI
    @Override
    protected void onProgressUpdate(Bitmap... images){
        if(images[0] != null)
            this.view.setImageBitmap(images[0]);
        lastUpdateTimestamp = System.currentTimeMillis();
    }
    @Override
    protected void onPostExecute(Void unused){
        bitmap.recycle();
    }
    public void stopDownloading(){
        running = false;
    }
}

停止下载

getImageInstance.stopDownloading();

我不知道你的应用程序能做什么,但用户不会喜欢下载不必要的图像,这会占用他们的数据量,也许可以考虑一种更好的方法来做你想做的事情。

最新更新