【发布时间】:2011-11-09 14:24:16
【问题描述】:
我已经阅读了 100 多篇关于 OOM 问题的文章。大多数是关于大位图的。我正在做一个地图应用程序,我们在其中下载256x256 天气叠加图块。大多数都是完全透明的并且非常小。我刚刚在调用 BitmapFactory.decodeByteArray(....). 时遇到了 442 字节长的位图流崩溃
例外状态:
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 的地方。我刚刚回答的一个最近的 SO 问题说明了这种情况 stackoverflow.com/questions/7136198/…,其中 OOM 不一定是由引发错误的 Activity 引起的。
-
SO 上已经有很多与这个问题相关的答案,这是应该适合您的解决方案之一。 Memory exceeds 更新: 另一个不错的答案在这里,Memory Leaks
标签: android memory bitmap out-of-memory bitmapfactory