2012-07-12 63 views
0

我使用这个工具如何从网站加载图片时减少内存?

public class Util_ImageLoader { 
public static Bitmap _bmap; 

Util_ImageLoader(String url) { 
    HttpConnection connection = null; 
    InputStream inputStream = null; 
    EncodedImage bitmap; 
    byte[] dataArray = null; 

    try { 
     connection = (HttpConnection) Connector.open(url + Util_GetInternet.getConnParam(), Connector.READ, 
       true); 
     inputStream = connection.openInputStream(); 
     byte[] responseData = new byte[10000]; 
     int length = 0; 
     StringBuffer rawResponse = new StringBuffer(); 
     while (-1 != (length = inputStream.read(responseData))) { 
      rawResponse.append(new String(responseData, 0, length)); 
     } 
     int responseCode = connection.getResponseCode(); 
     if (responseCode != HttpConnection.HTTP_OK) { 
      throw new IOException("HTTP response code: " + responseCode); 
     } 

     final String result = rawResponse.toString(); 
     dataArray = result.getBytes(); 
    } catch (final Exception ex) { 
    } 

    finally { 
     try { 
      inputStream.close(); 
      inputStream = null; 
      connection.close(); 
      connection = null; 
     } catch (Exception e) { 
     } 
    } 

    bitmap = EncodedImage 
      .createEncodedImage(dataArray, 0, dataArray.length); 
    int multH; 
    int multW; 
    int currHeight = bitmap.getHeight(); 
    int currWidth = bitmap.getWidth(); 
    multH = Fixed32.div(Fixed32.toFP(currHeight), Fixed32.toFP(currHeight));// height 
    multW = Fixed32.div(Fixed32.toFP(currWidth), Fixed32.toFP(currWidth));// width 
    bitmap = bitmap.scaleImage32(multW, multH); 

    _bmap = bitmap.getBitmap(); 
} 

public Bitmap getbitmap() { 
    return _bmap; 
} 
} 

当我把它其中包含10个孩子的一个listfield,则日志口口声声说failed to allocate timer 0: no slots left

这意味着内存已经用完,没有更多的内存再次分配,因此我的主屏幕无法启动。

+0

@Nate,我需要你的帮助。 – 2012-07-12 10:43:24

+0

请参阅[我对最近提出的问题的回复](http://stackoverflow.com/a/11482986/119114),它也使用了Util_ImageLoader。在这个回应中,我提供了一个完整的代码,用于替代实现,这应该有所帮助谢谢。似乎可以理解 – Nate 2012-07-14 10:55:07

回答

2

在你的记忆中的下列对象在同一时间:

// A buffer of about 10KB 
    byte[] responseData = new byte[10000]; 

    // A string buffer which will grow up to the total response size 
    rawResponse.append(new String(responseData, 0, length)); 

    // Another string the same length that string buffer 
    final String result = rawResponse.toString(); 

    // Now another buffer the same size of the response.   
    dataArray = result.getBytes(); 

它总,如果你下载ñASCII字符,你同时有10KB,加上2 * n个字节的第一个Unicode字符串缓冲区,在result字符串中加上2 * n个字节,再加上dataArray中的n个字节。如果我没有错,总和可达5n + 10k。有优化的空间。

一些改进是:

  • 检查响应代码,然后再读取流,如果响应代码为HTTP 200无需阅读,如果服务器返回错误。
  • 摆脱字符串。如果之后再次转换为字节,则无需转换为字符串。
  • 如果图像很大,请不要在下载时将它们存储在RAM中。相反,打开FileOutputStream并在从输入流中读取时写入临时文件。然后,如果临时图像仍然足够大以显示,则缩小它们。
+0

,但不知道它的代码 – 2012-07-12 10:27:16