我已閱讀100篇關於OOM問題的文章。大多數是關於大型位圖的。我正在做一個地圖應用程序,我們下載256x256
天氣疊加圖塊。大多數都是完全透明和非常小的。我剛剛得到的,這是442個字節長的位圖流的碰撞,同時呼籲BitmapFactory.decodeByteArray(....).
Android - BitmapFactory.decodeByteArray - OutOfMemoryError(OOM)
的異常狀態:
java.lang.OutOfMemoryError: bitmap size exceeds VM budget(Heap Size=9415KB, Allocated=5192KB, Bitmap Size=23671KB)
的代碼是:
protected Bitmap retrieveImageData() throws IOException {
URL url = new URL(imageUrl);
InputStream in = null;
OutputStream out = null;
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// determine the image size and allocate a buffer
int fileSize = connection.getContentLength();
if (fileSize < 0) {
return null;
}
byte[] imageData = new byte[fileSize];
// download the file
//Log.d(LOG_TAG, "fetching image " + imageUrl + " (" + fileSize + ")");
BufferedInputStream istream = new BufferedInputStream(connection.getInputStream());
int bytesRead = 0;
int offset = 0;
while (bytesRead != -1 && offset < fileSize) {
bytesRead = istream.read(imageData, offset, fileSize - offset);
offset += bytesRead;
}
// clean up
istream.close();
connection.disconnect();
Bitmap bitmap = null;
try {
bitmap = BitmapFactory.decodeByteArray(imageData, 0, bytesRead);
} catch (OutOfMemoryError e) {
Log.e("Map", "Tile Loader (241) Out Of Memory Error " + e.getLocalizedMessage());
System.gc();
}
return bitmap;
}
這是我在看調試器:
bytesRead = 442
所以位圖數據是442字節。爲什麼它會試圖創建一個23671KB位圖並耗盡內存?
事情需要注意的是,一些OOM並不必然導致通過觸發錯誤的頁面。有時候,OOM是由以前的活動/錯誤累積而觸發的,這些活動/錯誤是由位圖操作偶然觸發的。我們應該將應用視爲一個整體,而不是觸發OOM的地方。最近的一個問題,我剛剛回答說明了這個場景http://stackoverflow.com/questions/7136198/android-many-outofmemoryerror-exceptions-only-on-single-activity-with-mapview/7154643#7154643其中OOM是不一定是由拋出該錯誤的活動引起的。 – momo
在這個問題上已經有很多關於這個問題的答案,這裏是適合你的解決方案之一。 [內存超過](http://stackoverflow.com/questions/477572/android-strange-out-of-memory-issue/823966#823966)**更新:**另一個不錯的答案是在這裏,[內存泄漏]( HTTP://友的解決方案。blogspot.com/2010/08/how-to-if-you-want-to-create-and.html) –