I have an Activity A start Activity B in my App. When my App is stopped and the memory of the android system is low, my App will be cleared from the back stack. When I launch my App again, an exception occur during instantiate Activity B. So I want to make sure Activity B is finished when the memory is low, thus the exception will not occur. I have tried putting finish() in onMemoryLow(), but it didn't work. What else can I do?
Android just kills your process if it is in the background. When the user returns to the app, Android recreates the process and recreates the Activity that was on the top of the activity stack. You need to program your activities so that they can run like this (ie: being recreated after a restart). If you can't do this you can try the following:
Create a class with static variable like this:
public class Globals {
public static boolean initialized;
}
The variable Globals.initialized
will have the value false
when the process is created (or recreated).
Now, in your ActivityA
, when you set up the data that ActivityB
relies on, you can set the initialized flag, like this:
Globals.initialized = true;
In ActivityB.onCreate()
, check the value of initialized
and if it isn't set, just call finish()
which will take the user back to ActivityA
, like this:
if (!Globals.initialized) {
finish(); // Process was recreated while ActivityB was on top of the stack,
// so finish now
return;
}