Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent Android OS from closing a background app for memory?

I created an app that uses ~10MB of RAM. It seems that when I start other apps and my app is in the background, it sometimes closes. I suspect this is because Android OS closes background apps for RAM management purposes (Phone have 1024MB of total RAM).

Is there any way that I can keep my app always running in the background programmatically or otherwise?

like image 418
user2510325 Avatar asked Jan 09 '23 01:01

user2510325


2 Answers

You cant keep your app alive in the background over the wishes of the OS. The best thing you can do is save and restore the state of your activities/fragments/views etc.

Recreating an Activity

static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...

//saving
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    // Save the user's current game state
    savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
    savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);

    // Always call the superclass so it can save the view hierarchy state
    super.onSaveInstanceState(savedInstanceState);
}

//restoring
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); // Always call the superclass first

    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
    } else {
        // Probably initialize members with default values for a new instance
    }
    ...

}

like image 194
Eoin Avatar answered Apr 09 '23 13:04

Eoin


Use Service to run in Background.

Read more at Run Background Service.

like image 33
89030943809 Avatar answered Apr 09 '23 14:04

89030943809