Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/heroku/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何使用AsyncTask将图像从后台线程发送到UI线程?_Android_Android Asynctask - Fatal编程技术网

Android 如何使用AsyncTask将图像从后台线程发送到UI线程?

Android 如何使用AsyncTask将图像从后台线程发送到UI线程?,android,android-asynctask,Android,Android Asynctask,我正在使用AsyncTask下载图像,并希望将下载的图像发送到UI线程。这是它的代码 public class DownloadImageTask extends AsyncTask<URL, Void, Drawable>{ @Override protected Drawable doInBackground(URL... imgURL) { // TODO Auto-generated method stub InputStre

我正在使用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;
        }       
    }
}   
公共类下载ImageTask扩展异步任务{
@凌驾
受保护的可绘制doInBackground(URL…imgURL){
//TODO自动生成的方法存根
输入流输入;
位图;
可抽出式d;
试一试{
//in=(InputStream)imgURL[0]。getContent();
bitmap=BitmapFactory.decodeStream(imgURL[0].openConnection().getInputStream());
d=(可绘制)新位图可绘制(位图);
返回d;
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
返回null;
}       
}
}   

谢谢。

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

类下载任务扩展了AsyncTask {

检查此代码,因为您无法从doInBackGround()设置图像

但是,如果你想设置它,有两种方法

  • 在此线程上使用OnProgressUpdate()方法,或
  • 尝试方法Activity.runOnUiThread(){}thro',它将与UI线程交互
  •     @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); 
    
        }
    }