如何实现从AsyncTask中的URL下载图像的方法

时间:2014-10-18 12:20:48

标签: android android-image

我使用此方法下载图片

public static Bitmap getBitmapFromURL(String u, int width, int height) {
        try {

            URL url = new URL(u);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream input = connection.getInputStream();

            // First decode with inJustDecodeBounds=true to check dimensions
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(input, null, options);

            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, width, height);

            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;
            return BitmapFactory.decodeStream(input, null, options);

        } catch (IOException e) {
            // Log exception
            return null;
        }     
    }

此方法和位图在Adapter中用于显示每个列表项的图像:

Bitmap bitmap = PickanteHelper.getBitmapFromURL(image_url, 150, 150);
holder.itemImage.setImageBitmap(bitmap);

为了避免NetworkOnMainThread异常,我想我应该在加载每个图像时使用AsyncTask吗?

2 个答案:

答案 0 :(得分:0)

试试这个。

为什么不使用通用图片加载器

    // UNIVERSAL IMAGE LOADER SETUP
    DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheOnDisc(true).cacheInMemory(true)
            .imageScaleType(ImageScaleType.EXACTLY)
            .displayer(new FadeInBitmapDisplayer(300)).build();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
            getApplicationContext())
            .defaultDisplayImageOptions(defaultOptions)
            .memoryCache(new WeakMemoryCache())
            .discCacheSize(100 * 1024 * 1024).build();

参考以下示例

http://javatechig.com/android/universal-image-loader-library-in-android

https://github.com/nostra13/Android-Universal-Image-Loader

答案 1 :(得分:0)

尝试这样的事情:

private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();

//forming a HttoGet request 
final HttpGet getRequest = new HttpGet(url);
try {
    HttpResponse response = client.execute(getRequest);
    //check 200 OK for success
    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode != HttpStatus.SC_OK) {
        Log.w("ImageDownloader", "Error " + statusCode + 
                " while retrieving bitmap from " + url);
        return null;
    }

    final HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream inputStream = null;
        try {
            // getting contents from the stream 
            inputStream = entity.getContent();
            // decoding stream data back into image Bitmap that android understands
            final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            return bitmap;
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            entity.consumeContent();
        }
    }
} catch (Exception e) {
    // You Could provide a more explicit error message for IOException
    getRequest.abort();
    Log.e("ImageDownloader", "Something went wrong while" +
            " retrieving bitmap from " + url + e.toString());
} 
return null;
}