I have 4 Different Activities, and going through the links I have created a Sample for the same.
Objective:
Activities A,B,C,D;
A -> B -> C -> D
An event in D causes C and D to pop Leaving A and B in stack.
An event in D may cause B C and D to POP leaving only A in stack.
Implementation:
I use the following Event for my First Three Activities i.e. A B C
if(v==buttonNext){
Intent secondAct=new Intent(FirstActivity.this, SecondActivity.class);
//storing the Stack
MaintainMyStack.addBackActivity(this);
startActivity(secondAct);
}
I use the following Event for my Forth Act. i.e. D
if(v==btnBack){
finish();//finishes "D"
Activity act=MaintainMyStack.getBackActivity();
act.finish(); //finishes last in stack i.e. "C"
}
I use this Common Class Amongst My A B C D Activities.
public class MaintainMyStack {
private static Stack<Activity> classes = new Stack<Activity>();
public static Activity getBackActivity() {
return classes.pop();
}
public static void addBackActivity(Activity c) {
classes.push(c);
}
}
It works as desired, but I am just concerned about the MaintainMyStack class might Leak Memory when it meets real Scenerio, Please suggest should I go with this approach or Do we have other options to implement the same.
How can i create the MaintainMyStack have just one instance without leaking any memory
You should have a look at the
Intentsflag FLAG_ACTIVITY_CLEAR_TOP. Adding this flag to yourIntentwill do exactly what you are trying to achieve with your own activity stack, and you won’t need that anymore.