canvas:尝试在asynctask上使用循环位图android.graphics.Bitmap

时间:2014-07-21 05:31:28

标签: android bitmap android-asynctask

尝试使用Asynctask从URL检索图像时出现此错误。 这是我的asynctask:

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap result = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            result = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
        if (result != null && !result.isRecycled()) {
            result.recycle();
            result = null;
        }
    }
}

如果我删除result.recycle(),则错误将是OutofMemoryError。 我正在从不同的网址中检索多个图片。 我怎样才能做到这一点? 我通过以下方式调用asynctask:

new DownloadImageTask(imageview[i]).execute(paths.get(i));

非常感谢,:))

2 个答案:

答案 0 :(得分:1)

由于您仍需要位图,因此无法在此处进行回收。问题是这些位图使用的内存总量大于可用内存总量(当添加到应用程序已使用的内存时)。正因为如此,1人给出使用图书馆的建议不会有帮助 - 它不会增加记忆。以下是您可以做的一些事情:

1)减少应用程序使用的内存。可能或可能不可能,查看堆分析器,看看是否有内存泄漏。

2)请勿一次下载所有图像。

3)不要将它们下载到内存中,而是将其写入文件并仅在实际需要时打开每个图像。这可以与LRUCache结合使用,以确保您永远不会使用超过固定数量的内存。

答案 1 :(得分:-2)

使用picasa库

 ImageView product_image = (ImageView) itemview
            .findViewById(R.id.product_image);
Picasso.with(context)
        .load(product_order_details.get(position).product_image)
        .placeholder(R.drawable.defalutimage).fit().into(product_image);