简体   繁体   中英

android async image url loading

I have a custom ImageView subclass that I am using to fetch images in URL using an AsyncTask. However it seems that no matter what I do, the list view population is paused until the image is fetched.

public void setImageURL(final String url) {
    // do we have url in the cache?
    Bitmap bitmap = mCache.getBitmap(url);
    if(bitmap == null) {
        new AsyncTask<Void, Void, Bitmap>() {
            protected Bitmap doInBackground(Void... p) {
                Bitmap bm = null;
                try {
                    URL aURL = new URL(url);
                    URLConnection conn = aURL.openConnection();
                    conn.setUseCaches(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bm = BitmapFactory.decodeStream(bis);
                    bis.close();
                    is.close();
                } catch(IOException e) {
                    e.printStackTrace();
                }

                if(bm == null) {
                    return null;
                }
                return bm;
            }

            protected void onPostExecute(Bitmap bmp) {
                if(bmp == null) {
                    return;
                }
                mCache.cacheBitmap(url, bmp);
                setImageBitmap(bmp);
            }
        }.execute();
    } else {
        setImageBitmap(bitmap);
    }
}

Why should an async task block anything to do with the list population?

Are you starting multiple AsyncTasks? I would implement it to only use 1 AsyncTask that loads all images. A lot of time will be spent allocating and starting new Threads for each image.

http://developer.android.com/training/displaying-bitmaps/process-bitmap.html will get you started. However be sure to account for things like how a ListView reuses views as it scrolls. You don't always have a simple 1 view to 1 bitmap pair.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM