2011-05-16 152 views
3

你好我有一个位图的Hasmap,我需要在Android设备上存储下一个应用程序启动时使用的位图。Android HashMap序列化/反序列化

我的HashMap是这样的,并且包含多达1000位图:

private static HashMap <String, Bitmap> cache = new HashMap<String, Bitmap>(); 
+0

会对同一个uqestions感兴趣.. – cV2 2011-08-01 01:24:54

回答

0

你可能要考虑创建地图的扩展(通过使用AbstractMap),并覆盖相关的功能。通常,扩展的结构应具有:

  1. 使用常规映射的内存硬缓存。这应该是大小绑定的缓存对象。你可以利用的LinkedHashMap并覆盖removeEldesEntry(),以检查是否超过了尺寸

    this.objectMap = Collections.synchronizedMap(new LinkedHashMap() { 
     @Override 
     protected boolean removeEldestEntry(LinkedHashMap.Entry eldest) { 
      if (size() > HARD_CACHE_CAPACITY) { 
       // remove from cache, pass to secondary SoftReference cache or directly to the disk 
      } 
     } 
    }); 
  1. 如果超出缓存,然后把它放到磁盘
  2. 覆盖get函数执行以下操作:在初始获取时,根据特定的命名约定(与密钥相关)从磁盘加载位图并将其存储在内存中。大致类似的信息(请原谅任何语法错误)


    @Override 
    public Bitmap get(Object key) { 
     if(key != null) { 
      // first level, hard cache 
      if(objectMap.containsKey(key)) { 
       return objectMap.get(key); 
      } 

      // soft reference cache 
      if(secondaryCache.containsKey(key)) { 
       return secondaryCache.get(key); 
      } 

      // get from disk if it is not in hard or soft cache 
      String fileName = "Disk-" + key + ".txt"; 
      File f = new File(cacheDir, fileName); 

      if(f.exists()) { 
       // put this back to the hard cache 
       Bitmap object = readFromReader(f); 

       if(object != null) { 
        objectMap.put((String)key, object); 
        return object; 
       } 
      } 
     } 


     return null; // unable to get from any data source 
    } 

同样你放有被override把磁盘供以后使用,所以当你重新初始化您的应用程序,你可以只创建地图的一个实例延期。如果你愿意,你也可以预先加载应用程序中最近使用的项目的散列表。基本上,通过扩展AbstractMap,您可以获得灵活性,而不会使用那1000个位图来消除内存。希望这可以帮助