我已经阅读了 100 篇关于 OOM 问题的文章。大多数是关于大位图的。我正在做一个地图应用程序,我们在其中下载256x256
天气叠加图块。大多数都是完全透明的并且非常小。我刚刚在调用时遇到了 442 字节长的位图流崩溃BitmapFactory.decodeByteArray(....).
例外规定:
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 位图并耗尽内存?