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
Along with onLowMemory()
and onTrimMemory()
, which monitor system memory, here's a way to monitor app memory. It uses Zsolt Safrany's answer at it's core.
private final float CHECK_MEMORY_FREQ_SECONDS = 3.0f;
private final float LOW_MEMORY_THRESHOLD_PERCENT = 5.0f; // Available %
private Handler memoryHandler_;
public void onCreate( Bundle savedInstanceState ) {
// Do Stuff...
// Start Monitoring App Memory Availablity
memoryHandler_ = new Handler();
checkAppMemory();
}
public void checkAppMemory(){
// Get app memory info
long available = Runtime.getRuntime().maxMemory();
long used = Runtime.getRuntime().totalMemory();
// Check for & and handle low memory state
float percentAvailable = 100f * (1f - ((float) used / available ));
if( percentAvailable <= LOW_MEMORY_THRESHOLD_PERCENT )
handleLowMemory();
// Repeat after a delay
memoryHandler_.postDelayed( new Runnable(){ public void run() {
checkAppMemory();
}}, (int)(CHECK_MEMORY_FREQ_SECONDS * 1000) );
}
public void handleLowMemory(){
// Free Memory Here
}