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?
2 Answers
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);
4 Comments
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?
InputStream)? Maybe try that. 60MB is a lot for any app to have without garbage collecting. I would expect Android to lease that much data at any one point in the app anyways. You could also try separating the data into an array of byte arrays.