My application has a lot of images and sometimes it crashes due to low memory.
I wrote this function that I found on the developer site.
public void onLowM
As explained at android developers is hard to determine how much memory we have available for our app since: The exact heap size limit varies between devices based on how much RAM the device has available overall
. So is a better approach to ask if we are running in a lowMemory
environment using ActivityManager.MemoryInfo
before doing a memory heavy operation like downloading an image or trying to load an image into memory, by doing this you will prevent OutOfMemoryExceptions
public void doSomethingMemoryIntensive() {
// Before doing something that requires a lot of memory,
// check to see whether the device is in a low memory state.
ActivityManager.MemoryInfo memoryInfo = getAvailableMemory();
if (!memoryInfo.lowMemory) {
// Do memory intensive work ...
}
}
// Get a MemoryInfo object for the device's current memory status.
private ActivityManager.MemoryInfo getAvailableMemory() {
ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
return memoryInfo;
}