Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to finish() two activities at the same time?

I am writing a math app for little kids to learn maths. It first prompts the user to select what kind of questions they want (MainActivity), and then it shows a bunch of questions (QuestionsActivity). After answering 10 questions, it tells you which question(s) did you answer correctly and which you didn't (ResultsActivity).

I know that Android puts all the activities on a stack. In my case, it would look like this:

ResultsActivity
QuestionsActivity
MainActivity

And when you call finish, an activity is popped from the stack. I want there to be a back to main menu button in the ResultsActivity to go back to the MainActivity. However, if I call finish in the ResultsActivity, the user would see QuestionsActivity! So how am I going to call finish on the both activities?

like image 1000
Sweeper Avatar asked Aug 26 '15 05:08

Sweeper


People also ask

How do you finish multiple activities?

When the user is on Activity D and click a button called exit, the application should go back to Activity B and finish the Activities C and D.

How do you finish an activity?

On Clicking the back button from the New Activity, the finish() method is called and the activity destroys and returns to the home screen.

What is finishAffinity?

finishAffinity() : finishAffinity() is not used to "shutdown an application". It is used to remove a number of Activities belonging to a specific application from the current task (which may contain Activities belonging to multiple applications).


2 Answers

Two options:

  1. Call finish() in QuestionsActivity after you make the call to start the ResultsActivity. This will remove it from the stack so that pressing back from ResultsActivity returns to MainActivity.
  2. Use Intent.FLAG_ACTIVITY_CLEAR_TOP in the intent to go back to MainActivity. This will clear all activities that are on top of it.
like image 70
Karakuri Avatar answered Sep 19 '22 17:09

Karakuri


You can clear your stack by simple starting your MainActivity again and clearing the stack with the following flags:

  final Intent intent = new Intent(context, MainActivity.class);
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(intent);
like image 31
Christopher Avatar answered Sep 18 '22 17:09

Christopher