问题
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