Android 图片需要很长时间才能从 URL 获取

Android Image taking a long time to get from URL

目前我正在从 url 加载图像,它需要很长时间,我无法弄清楚为什么,有时需要超过 60 秒才能获得并不是那么大的图像。

我的代码:

获取图像异步任务:

public class GetImageAsyncTask extends AsyncTask<Void, Void, Bitmap> {

String url;
OnImageRetrieved listener;
ImageView imageView;
int height;
int width;

public GetImageAsyncTask(String url, ImageView imageView,OnImageRetrieved listener, int height, int width) {
    this.url = url;
    this.listener = listener;
    this.imageView = imageView;
    this.height = height;
    this.width = width;
}

public interface OnImageRetrieved {
    void onImageRetrieved(Bitmap image, ImageView imageview, String url);
}

protected Bitmap doInBackground(Void... params) {

    Bitmap image = null;

    try {
        image = ImageUtilities.decodeSampledBitmapFromUrl(this.url, this.width, this.height);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return image;
}

    protected void onPostExecute(Bitmap result) {
        this.listener.onImageRetrieved(result, this.imageView, this.url);
    }
}

 public static Bitmap decodeSampledBitmapFromUrl(String url, int reqWidth, int reqHeight) throws IOException {

    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;

    BitmapFactory.decodeStream(new java.net.URL(url).openStream(), null, options);

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

    options.inJustDecodeBounds = false;

    return BitmapFactory.decodeStream(new java.net.URL(url).openStream(), null, options);
}

获取样本量:

public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {

    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
}

使用这些方法是因为如果不这样做可能会出现内存并发症,但似乎花费的时间太长了。是否有一些我只是没有看到的非常繁重的计算?

你可以使用 Picasso 或 volley 库加载 image.I 建议使用 volly 因为它是 google 自己引入的。

所以问题出在数组适配器上,事实上 getView() 可以被调用 100 次,可以同时下载接近 100mb 的数据。

因此,作为这种情况的临时修复,我实现了一个全局 LruCache 单例,我在开始异步任务之前首先检查它。

这显然不理想,但现在必须这样做。我确信有更好的解决方案,如果有人可以提供,我很乐意听取他们的意见。