0

I have an initial activity O and one more activity A in which i can select to go to activities A1,A2,A3 and for example fill in a form in each of them. So i follow this path:

O>A>A1>A>A2>A>A3

While i am at A3 i want to press the back button and go to O again but i will have to pass from every instance of A (let's assume i use finish() or no history in the manifest for A1,A2,A3 so they will be not present in the stack)

how can i declare that A will only have one instance (the last one) in the stack, so that if i press back button twice i will go to O again?

David Wasser
  • 93,459
  • 16
  • 209
  • 274
mike_x_
  • 1,900
  • 3
  • 35
  • 69
  • Each time activity `A` appears is a new instance? Why not just have a single instance of activity `A` and go back to it from each of the other activities? – Bryan Dec 01 '16 at 13:36
  • this is default behavior. How can i make it single instance? that's the question... – mike_x_ Dec 01 '16 at 13:39
  • why do u need to create multiple instance of A? are u implementing logout functionalities? – Dilip Dec 01 '16 at 13:40
  • Are A1, A2, A3 and A all instances of the same `Activity` class? – David Wasser Dec 01 '16 at 15:56

2 Answers2

3
  @Override
public void onBackPressed() {
    Intent intent = new Intent(this,O.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
}
Prashanth Debbadwar
  • 1,047
  • 18
  • 33
  • 2
    While this answer is good, try to explain what the code does, to help other/new users understand how it works. Most Android begginners have problems understanding `Activity` and `Task` stacks. – Bonatti Dec 01 '16 at 13:37
1

Change the launchMode of activity A to singleTop. As it states in the documentation:

If an instance of the activity already exists at the top of the target task, the system routes the intent to that instance through a call to its onNewIntent() method, rather than creating a new instance of the activity.

Now, instead of going from A -> A1 -> A, you can just finish() activity A1 (or use the up button), which will return you to the instance of activity A.

Bryan
  • 14,756
  • 10
  • 70
  • 125