2012-02-14 47 views
0

我正在使用AsyncTask下载图像,并希望将下载的图像发送到UI线程。这是它的代码。如何使用AsyncTask将图像从后台线程发送到UI线程?

public class DownloadImageTask extends AsyncTask<URL, Void, Drawable>{ 

    @Override 
    protected Drawable doInBackground(URL... imgURL) { 
     // TODO Auto-generated method stub 
     InputStream in; 
     Bitmap bitmap; 
     Drawable d; 
     try { 
      //in = (InputStream) imgURL[0].getContent(); 
      bitmap = BitmapFactory.decodeStream(imgURL[0].openConnection().getInputStream()); 
      d =(Drawable)new BitmapDrawable(bitmap); 
      return d; 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
      return null; 
     }  
    } 
} 

谢谢。

回答

2

doInBackround()执行后返回的值将被传递到onPostExecute()AsynkTask,所以你应该重写onPostExecute()方法,在那里你会收到你的Drawable。请注意,onPostExecute()onPreExecute()在UI线程上运行,因此您可以从这两种方法修改/更新UI。

0

类DownloadTask扩展的AsyncTask {

@Override 
    protected Boolean doInBackground(Url... url) { 
     Bitmap b = 
          // do some bitmap downloader code from web url 

     return b; 
    } 

    @Override 
    protected void onPostExecute(Bitmap image) { 

     imageView.setImageBitmap(image); 

    } 
} 

赤出这个代码,因为你无法从doInBackGround()设置图像....

但还是如果u要设置有2种方式。

  1. 使用OnProgressUpdate()在此线程方法或
  2. 试方法Activity.runOnUiThread(){}救援人员到场”,其将与UI线程交互