【问题标题】:open many activities with bitmaps recursively递归地使用位图打开许多活动
【发布时间】:2015-06-09 10:22:54
【问题描述】:

我的应用程序出现问题:在我的应用程序中,每个activity 都有多个ImageViews,每个ImageView 都设置了一个bitmap。如果打开多个activities recursively分配内存会不断增加,最后MemoryCache已满,所以我无法显示任何位图,否则应用程序将crash

我可以对activity 停止的ImageView 做什么?我可以recyclebitmap,并在其活动恢复后重新加载位图吗?

我正在使用 Fresco 来处理位图加载和缓存。

【问题讨论】:

  • 换句话说:我在处理位图时遇到 OOMException,但我试图变得聪明并没有提及这一点,因为这样的问题将被标记为重复
  • @Syed Raza Mehdi 我想知道的是:我可以对那些活动停止的位图做什么,例如活动 A 开始活动 B,现在 A 停止并且看不到。在这种情况下,我可以为 A 的 ImageView 设置空位图并在 A 回来时加载位图。我是新来的,对不起我的英语不好

标签: android bitmap


【解决方案1】:

在使用Bitmap 对象时处理内存的最佳方法是使用LruCache 并将Bitmap 存储在其中。 一旦您不再需要您的Bitmap,您可以将其存储到您的缓存中并回收它以释放尽可能多的内存。如果它存储在缓存中,您只需从缓存中获取图像。

这是我处理缓存的类:

public class ImagesCache {
private  LruCache <String, Bitmap> imagesWarehouse;
private static ImagesCache cache;

public static ImagesCache getInstance() {
    if(cache == null)
        cache = new ImagesCache();
    return cache;
}

public void initializeCache() {
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;

    imagesWarehouse = new LruCache<String, Bitmap>(cacheSize) {
        protected int sizeOf(String key, Bitmap value) {
            // The cache size will be measured in kilobytes rather than number of items.
            int bitmapByteCount = value.getRowBytes() * value.getHeight();

            return bitmapByteCount / 1024;
        }};
}

public void addImageToWarehouse(String key, Bitmap value) {       
    if (imagesWarehouse != null && imagesWarehouse.get(key) == null)
        imagesWarehouse.put(key, value);
}

public Bitmap getImageFromWarehouse(String key) {
    if (key != null)
        return imagesWarehouse.get(key);
    else
        return null;
}

public void removeImageFromWarehouse(String key) {
    imagesWarehouse.remove(key);
}

public void clearCache() {
    if (imagesWarehouse != null)
        imagesWarehouse.evictAll();
}

}

记得在应用启动时初始化缓存

cache.initializeCache()

并清除您的应用何时完成

cache.clearCache()

【讨论】:

  • 我正在使用Fresco 来完成这项工作。我的问题是:如何处理那些活动停止的位图(例如,它的活动开始另一个活动)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-04
  • 2016-08-13
  • 1970-01-01
  • 2021-07-23
  • 2015-09-07
相关资源
最近更新 更多