如何减少android中的内存消耗

时间:2013-02-02 12:27:10

标签: android memory-management out-of-memory

  

可能重复:
  Android: Strange out of memory issue while loading an image to a Bitmap object

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

请帮帮我

1 个答案:

答案 0 :(得分:1)

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指示运行垃圾收集器的好时机