tags:

views:

151

answers:

1

How to finish any previous activity in application stack (at any level , I mean not immediate parent) , from current activity like on some particular event I want to invalidate this previous activity? Any help ? Thanks.

+1  A: 

You can use the Intent flag FLAG_ACTIVITY_CLEAR_TOP to restart an activity from the stack and clear everything that was above it. This isn't quite what you're asking, but it might help.

To do this, use:

Intent intent = new Intent(context, classToBeStarted.class);
intent.setFlag(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Steve H
I'm having the same problem. First I start activities A, B and C. Then I start activity D with Intent.FLAG_ACTIVITY_CLEAR_TOP set. This should make D the only activity on the stack, right? Somehow this is not the case, because when I press the back button, I go back to one of the previous activities.
neu242
No, that's not how CLEAR_TOP works. CLEAR_TOP removes anything that is 'above' the target activity in the stack. So if you have A, B, C and then you start A again with CLEAR_TOP, then B and C get killed. If you started D or restarted C, nothing would happen. That's why I said that it isn't quite what he was asking for, but it can be useful. For example, if you have a main menu screen that will be the root activity, you can relaunch it with CLEAR_TOP whenever the user returns to it to kill everything else.
Steve H
So to achieve what I wanted, I might do something like this instead:1) Start A, B, C. 2) Start A with CLEAR_TOP and some data identifying D. 3) In A, call finish() and start D. Feels like a dirty hack, but should work..?
neu242
Actually I do not want to clear the whole stack.neu242 let me know if your way works ..but that would make user get moved from current focused activity, which I want to avoid. I have asked same question on http://www.coderanch.com/t/493238/Android/Mobile/Finish-any-previous-activity-stackgave some other possible ways.
mob_king