2012-07-12 57 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