android - 如何减少android中的内存消耗

标签 android memory-management out-of-memory

<分区>

Possible Duplicate:
Android: Strange out of memory issue while loading an image to a Bitmap object

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

请帮帮我

最佳答案

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

关于android - 如何减少android中的内存消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14661890/

相关文章:

c - malloc 和 calloc

python 脚本被 oom Killer 杀死

python - pickle 文件太大而无法加载

android - 如何在 Android 上获取 NetworkCapabilities 对象?

android - FrameLayout subview 在调整大小时未正确更新

android - 如何在 Android 中隐藏我的数据文件夹?

C结构内存管理

Android 应用程序被卡住 - Socket 异常

python - 创建一个引用计数的图形

java - 在 Android 上使用 Jackson 库解析大型 JSON 时出现内存不足错误