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;
}
}

listfield当我在包含 10 个孩子的情况下调用它时,日志一直显示failed to allocate timer 0: no slots left.

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

4

1 回答 1

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();

总共,如果你下载了 n 个 ascii 字符,你同时有 10KB,加上第一个 unicode 字符串缓冲区中的 2*n 个字节,result加上字符串中的 2*n 个字节,加上dataArray. 如果我没记错的话,总计为 5n + 10k。有优化的空间。

一些改进将是:

  • 先检查响应码,如果响应码是 HTTP 200 则读取流。如果服务器返回错误则无需读取。
  • 摆脱字符串。如果之后您再次转换为字节,则无需转换为字符串。
  • 如果图像很大,下载时不要将它们存储在 RAM 中。相反,当您从输入流中读取时,打开FileOutputStream并写入临时文件。然后,如果临时图像仍然大到可以显示,则缩小它们。
于 2012-07-12T08:25:11.960 回答