首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在android中减少内存消耗

如何在android中减少内存消耗
EN

Stack Overflow用户
提问于 2013-02-02 12:27:10
回答 1查看 2.8K关注 0票数 4

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

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

请帮帮我

EN

回答 1

Stack Overflow用户

发布于 2013-02-02 12:36:49

1)缩小和缩小图像大小

代码语言:javascript
复制
/**
 * 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指示运行垃圾收集器的最佳时机

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14661890

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档