finish() activity twice in android?
Asked Answered
F

2

7

Okay say your using a app, and you opened a new activity and then opened another, you can end the activity your on by using finish(); and your back one activity, but how can you go back two activities, all the way back to the first one? I know you could use:

Intent savedGameIntent = new Intent(v.getContext(), firstclass.class);
v.getContext().startActivity(savedGameIntent);

But is that the best way to do it?

Flofloat answered 29/5, 2012 at 23:42 Comment(0)
R
9

Use the flag Intent.FLAG_ACTIVITY_CLEAR_TOP.

  Intent intent = new Intent(this,A.class);
  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  startActivity(intent);

From the documentation:

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

So effectively, if you have A -> B -> C, and you intent to A with that flag set, B and C will close.

Rosabella answered 29/5, 2012 at 23:53 Comment(2)
That works perfect! Thank you :) The only thing is, it works great on my phone(Android 4.04), but crashes in a emulator(Android 2.3.3)! Do you think it will crash on all Android 2.3.3 devices?Flofloat
@WilliamL.: Assume "yes", and fix the bug that causes the crash.Complicity
T
7

I believe that will start a new activity, not back up to the original one. It sounds like you want to finish the last and middle activities. If you start the last activity with startActivityForResult, you can then override onActivityResult in the middle activity, and call finish() from there.

Trove answered 29/5, 2012 at 23:47 Comment(1)
Good logic. Thank you so much.Blistery

© 2022 - 2024 — McMap. All rights reserved.