I want to be able to control which activities the user can press the back button into, depending on where the user is currently. For example, I have Activities A, B, C, and D.
The user navigates (through buttons I provide) from Activity A, to B, to C, and finally, to D. If the user presses back any time before D, I want the normal back operation (if they press back on Activity C, they will be presented with B).
However, if they make it all the way to D, I want to finish activities B and C. Now, when the user clicks back, I want them to be presented with A.
This can be done easily by intercepting the Back button keypress event and providing your own handling code.
So in your Activity D, you will have the following code:
EDIT (due to misuderstanding):
You can pass the references to the Context of your previous activities in a Bundle as an extra inside the Intent you use to start your new Activities. I believe that Context is Parcelable, so you should be good. BTW, you need the Context of those Activities so that you can do something like
ActivityOneCOntext.finish ();.[[EDITED, NOT WORKING]]
However, you should be careful with these references, as each alive reference to an Activity’s Context prevents the garbage collector from releasing the resources allocated for that Activity. If your Activity finishes and you still keep a reference somewhere in another Activity, you will have a (sort of a) memory leak.
EDIT2:
Obviously the code above was not working.
You can use this method to get a reference to the current Activity’s parent’s Context:
So, needles to say, you can have a grand-parent’s context like this:
You can see the reference hare.