1

What is wrong with this code when I want to close all activities in a task?

public static void closeAllBelowActivities(Activity current)
{
    boolean flag = true;
    Activity below = current.getParent();
    if (below == null)
        return;
    System.out.println("Below Parent: " + below.getClass());
    while (flag) {
        Activity temp = below;
        try {
            below = temp.getParent();
            temp.finish();
        } catch (Exception e) {
            flag = false;
        }
    }
}

2 Answers2

1

The way android works is that activities live in a stack (which you may know) so if A calls B calls C calls D

The stack looks like

// D - Current 
// C
// B
// A

If all you are trying to do is make sure that C,B,A are not in the stack anymore then you should call finish() before calling the next activity

A.startActivity(B)
A.finsh()
  ---
  B.startActivity(C)
  B.finish()

And so on, so I guess the my next question is why are you trying to do that via the current activity vs. from the calling activity which is the way it was designed?

You can also use intent flags like FLAG_ACTIVITY_CLEAR_TOP to clear the history list of all but the newest activity, which maybe is what you are trying to do?

Idistic
  • 6,281
  • 2
  • 28
  • 38
  • I am trying to implement a logout behaviour. I had already implemented the FLAG_ACTIVITY_CLEAR_TOP | FLAT_ACTIVITY_SINGLE_TOP based solution. But I wanted to see if there is a better approach towards that. – Sharique Abdullah Jul 15 '11 at 04:46
  • Ok but that's not what your problem statement was, anyway glad you found a solution. – Idistic Jul 15 '11 at 06:02
1

The best way is for the activities to register for a Broadcast Receiver. See this question On logout, clear Activity history stack, preventing "back" button from opening logged-in-only Activites

Community
  • 1
  • 1
Stefan Bossbaly
  • 6,682
  • 9
  • 53
  • 82