OutOfMemoryError when loading large amount of data in Android

我与影子孤独终老i 提交于 2019-12-11 02:43:38

问题


I'm downloading a rather large file on the SD card of an Android device (~60MB). The download goes fine, but I need to pull this file in its entirety into memory. I know that's a huge chuck of memory for a smart phone, but I know my device has more than double that amount. Anyway, my actual problem is I get a OutOfMemoryError when reading the file into a byte array. Is there any way to increase the allocated memory for my application, or some way to "fake" reference the file yet keep the file in external storage without loading it into internal memory?


回答1:


Each Virtual Machine instance in Android has what they called a VM Budget. This basically is the max amount of memory the entire app can occupy and nothing more. getRuntime().maxMemory() will give you the vm budget size for your current instance.

The budget can go anywhere from 16MB (G1) to 48MB (Moto Xoom) I think. Those numbers could be different as I'm trying to remember off the top of my head.

Usually for something like this you'd read the data in as an InputStream and process the data as you read it but don't retain the data itself.

If this is a Bitmap. You can use...

BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4; // Divides the width and height each by 4 when reading the data in.
Bitmap bitmap = BitmapFactory.decodeFile(String "filePath", options);
Bitmap bitmap = BitmapFactory.decodeStream(InputStream "fileStream", options);



回答2:


The simple answer is: You should really reconsider your current design. Could you explain why you would need to load 60mb of data into memory?



来源:https://stackoverflow.com/questions/6529586/outofmemoryerror-when-loading-large-amount-of-data-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!