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?
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
}
...
}
Use Service to run in Background.
Read more at Run Background Service.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With