No. You don't have to call finish()
on each of your Activity
transitions as Android handles the stack properly. However, you might need the explicit finish()
call in several places. For example,
- While you are starting an
Activity
by calling startActivityForResult
and from the Activity
started, you want to pass the result back to the calling Activity
using setResult
. Then you might need finish()
the Activity
started after sending the result to the calling Activity
in some cases.
- When you are opening a
DialogActivity
, you might have some logic on which you want the DialogActivity
to disappear. Then you call the finish()
function explicitly.
- A fullscreen
Activity
, might require disabling the onBackPressed
, as you are going to close the Activity
using a close button. In that case you need to call the finish()
method explicitly on pressing the close button in your Activity
.
If you intend to close all other Activity
in the back stack, while starting a specific Activity
, you don't need to call the finish()
method either after starting each Activity
that requires to go to that specific Activity
. You just have to change the launchMode
of that specific Activity
in the manifest file to do so.
<activity
android:name=".ClearBackStackActivity"
android:label="You want to clear the back stack of activities"
android:launchMode="singleTask">
Update
So for clarification, I have a quiz activity that allows you to answer
questions. When you submit the quiz you are taken to a results
activity. Ideally, would I want to set the quiz activity itself to be
cleared after the results are tallied and passed to the results
activity? Would that achieve the desired goal and be memory efficient?
I don't know if this makes sense what I'm asking here.
As far as I have understood, you want to clear the quiz activity after all answers are submitted and you have moved the user to the result activity. In this specific case, I can suggest you two different ways.
- You might consider having a
ResultActivity
as your launcher. To start the quiz you might consider staring the QuizActivity
using startActivityForResult
and then after the answers in the QuizActivity
are submitted, you are calculating the score and pass the score to the ResultActivity
again using setResult
from your QuizActivity
and then call finish()
method on your QuizActivity
. You will be receiving the score passed from QuizActivity
in the onActivityResult
function in your ResultActivity
.
- The other way of doing this is having a
QuizActivity
as launcher which will have the questions and after submitting the answers, the score will be calculated and the ResultActivity
will be opened with the score earned. I would like to suggest both of the activities to have launchMode=SingleTask
. By clicking a button in the ResultActivity
will start another QuizActivity
.