0

我现在正在使用需要在 AsyncTask 中的 LoadImageFromWeb 处理 ImageView。我没有 AsyncTask 的代码是这样的:

private void satellite() {
        // TODO Auto-generated method stub
    ImageView imgView =(ImageView)findViewById(R.id.satellite);
    Drawable drawable = LoadImageFromWeb("http://www.pagasa.dost.gov.ph/wb/sat_images/satellite.gif");
    imgView.setImageDrawable(drawable);

    }

我已经使用 AsyncTask 制作了一些其他程序,但它不同,因为它只使用字符串,我现在是 ImageView。

我搜索了答案,但他们的方法非常混乱。他们正在使用这样的东西:

public class MainActivity extends Activity {

ImageView mImgView1;
static Bitmap bm;
ProgressDialog pd;
String imageUrl = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mImgView1 = (ImageView) findViewById(R.id.mImgView1);
    pd = ProgressDialog.show(MainActivity.this, "Aguarde...",
            "Carregando...");
    new ImageDownload().execute("");
}

public class ImageDownload extends AsyncTask<String, Void, String> {

    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;
        loadBitmap(imageUrl, bmOptions);
        return imageUrl;
    }

    protected void onPostExecute(String imageUrl) {
        pd.dismiss();
        if (!imageUrl.equals("")) {
            mImgView1.setImageBitmap(bm);
        } else {
            Toast.makeText(MainActivity.this,
                    "Não foi possível obter resultados", Toast.LENGTH_LONG)
                    .show();
        }
    }

}

public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
        bm = BitmapFactory.decodeStream(in, null, options);
        in.close();
    } catch (IOException e1) {
    }
    return bm;
}

private static InputStream OpenHttpConnection(String strURL)
        throws IOException {
    InputStream inputStream = null;
    URL url = new URL(strURL);
    URLConnection conn = url.openConnection();

    try {
        HttpURLConnection httpConn = (HttpURLConnection) conn;
        httpConn.setRequestMethod("GET");
        httpConn.connect();

        if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            inputStream = httpConn.getInputStream();
        }
    } catch (Exception ex) {
    }
    return inputStream;
}

}

从我在 ImageView 上使用的方法来看,这非常复杂(对我来说)。

我的问题是:除了使用第二个代码之外,还有什么更简单、更容易的方法吗?我试着让它工作,但它没有。我不知道如何在图像方面执行 AsyncTask。我很沮丧。

我在这里先向您的帮助表示感谢 :)

4

2 回答 2

0

这里有很多答案,您可以从中导航到LazyLaoding其他图像加载库,但为什么您要采用更复杂的方式,因为您可以使用简单的 AsyncTask 实现直接完成。

只需将您的ImageView引用传递给.. _AsyncTask's ConstructordoInBackground()BitmaponPostExecute()Bitmap paramsNULLImageVIew

例子:

protected Bitmap doInBackground(String... params)

protected void onPostExecute(Bitmap bitmap)

于 2013-01-10T06:16:01.483 回答
0

这是您可以在您的项目中使用的类图像加载器,您只需要调用 Imageloader 的显示图像方法。

         public class ImageLoader {

MemoryCache memoryCache=new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews=Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService; 

public ImageLoader(Context context){
    fileCache=new FileCache(context);
    executorService=Executors.newFixedThreadPool(5);
}

final int stub_id = R.drawable.no_image;
public void DisplayImage(String url, ImageView imageView)
{
    imageViews.put(imageView, url);
    Bitmap bitmap=memoryCache.get(url);
    if(bitmap!=null)
        imageView.setImageBitmap(bitmap);
    else
    {
        queuePhoto(url, imageView);
        imageView.setImageResource(stub_id);
    }
}

private void queuePhoto(String url, ImageView imageView)
{
    PhotoToLoad p=new PhotoToLoad(url, imageView);
    executorService.submit(new PhotosLoader(p));
}

private Bitmap getBitmap(String url) 
{
    File f=fileCache.getFile(url);

    //from SD cache
    Bitmap b = decodeFile(f);
    if(b!=null)
        return b;

    //from web
    try {
        Bitmap bitmap=null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Exception ex){
       ex.printStackTrace();
       return null;
    }
}

//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
    try {
        //decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE=70;
        int width_tmp=o.outWidth, height_tmp=o.outHeight;
        int scale=1;
        while(true){
            if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
                break;
            width_tmp/=2;
            height_tmp/=2;
            scale*=2;
        }

        //decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize=scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}
    return null;
}

//Task for the queue
private class PhotoToLoad
{
    public String url;
    public ImageView imageView;
    public PhotoToLoad(String u, ImageView i){
        url=u; 
        imageView=i;
    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;
    PhotosLoader(PhotoToLoad photoToLoad){
        this.photoToLoad=photoToLoad;
    }


    public void run() {
        if(imageViewReused(photoToLoad))
            return;
        Bitmap bmp=getBitmap(photoToLoad.url);
        memoryCache.put(photoToLoad.url, bmp);
        if(imageViewReused(photoToLoad))
            return;
        BitmapDisplayer bd=new BitmapDisplayer(bmp, photoToLoad);
        Activity a=(Activity)photoToLoad.imageView.getContext();
        a.runOnUiThread(bd);
    }
}

boolean imageViewReused(PhotoToLoad photoToLoad){
    String tag=imageViews.get(photoToLoad.imageView);
    if(tag==null || !tag.equals(photoToLoad.url))
        return true;
    return false;
}

//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable
{
    Bitmap bitmap;
    PhotoToLoad photoToLoad;
    public BitmapDisplayer(Bitmap b, PhotoToLoad p){bitmap=b;photoToLoad=p;}
    public void run()
    {
        if(imageViewReused(photoToLoad))
            return;
        if(bitmap!=null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(stub_id);
    }
}

public void clearCache() {
    memoryCache.clear();
    fileCache.clear();
}

}

于 2013-01-10T06:18:29.083 回答