4

可能重复:
Android:将图像加载到位图对象时出现奇怪的内存不足问题

我是android领域的新手。我不知道如何减少android中的内存消耗。在我的应用程序中,大量图像是从网络中提取并显示到网格视图中的。运行应用程序时出现“内存不足问题”。

请帮我

4

1 回答 1

3

1)按比例缩小并减小图像的大小

/**
 * decodes image and scales it to reduce memory consumption
 * 
 * @param file
 * @param requiredSize
 * @return
 */
public static Bitmap decodeFile(File file, int requiredSize) {
    try {

        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(file), null, o);

        // The new size we want to scale to

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

        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;

        Bitmap bmp = BitmapFactory.decodeStream(new FileInputStream(file),
                null, o2);

        return bmp;

    } catch (FileNotFoundException e) {
    } finally {
    }
    return null;
}

2)使用bitmap.Recycle();

3)用于System.gc();向 VM 指示现在是运行垃圾收集器的好时机

于 2013-02-02T12:36:49.310 回答