Skip to content Skip to sidebar Skip to footer

Detect Whether Application Is Quit By The Os Because Of Low Ram

In the application I'm building, I need to detect the application quitting if and only if the application has been quit when its in the background because the OS is reclaiming memo

Solution 1:

Through trial and error I have worked out a solution that works perfectly for anyone thats interested. I have narrowed down the case when the application state is being resumed (onResume) in the case of the OS reclaiming memory.

publicboolean wasJustCollectedByTheOS = false; 

@OverridepublicvoidonSaveInstanceState(Bundle savedInstanceState)
{
    super.onSaveInstanceState(savedInstanceState);
    // this flag will only be present as long as the task isn't physically killed// and/or the phone is not restarted.
    savedInstanceState.putLong("semiPersistantFlag", 2L);
}

@OverridepublicvoidonRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    long semiPersistantFlag = savedInstanceState.getLong("semiPersistantFlag");
    if (semiPersistantFlag == 2L)
    {
        savedInstanceState.putLong("semiPersistantFlag", 0L);
        this.wasJustCollectedByTheOS = true;   
    }
}

// this gets called immediately after onRestoreInstanceState@OverridepublicvoidonResume() {
    if (this.wasJustCollectedByTheOS){
        this.wasJustCollectedByTheOS = false;
        // here is the case when the resume is after an OS memory collection    
    }
}

Solution 2:

I don't know whether its help you or not,

From Android Activity class,

publicvoidonLowMemory ()

This is called when the overall system is running low on memory, and would like actively running process to try to tighten their belt. While the exact point at which this will be called is not defined, generally it will happen around the time all background process have been killed, that is before reaching the point of killing processes hosting service and foreground UI that we would like to avoid killing.

Applications that want to be nice can implement this method to release any caches or other unnecessary resources they may be holding on to. The system will perform a gc for you after returning from this method.

And Since: API Level 14

publicabstractvoidonTrimMemory(int level)

Called when the operating system has determined that it is a good time for a process to trim unneeded memory from its process. This will happen for example when it goes in the background and there is not enough memory to keep as many background processes running as desired. You should never compare to exact values of the level, since new intermediate values may be added -- you will typically want to compare if the value is greater or equal to a level you are interested in.

Post a Comment for "Detect Whether Application Is Quit By The Os Because Of Low Ram"