TLDR: What is the difference between finishAffinity() and finishAndRemoveTask()?
I am working on an Android app that has one single activity, and uses fragment switching instead of new activities.
I was having a weird issue with a certain fragment living through the backstack even when clearing the backstack. Long story short, this fragment was living because I started a web browser from that fragment.
Using the popular press back x2 to exit the app technique in my main acitvity, it would 'exit' using finishAndRemove task. This would return to that certain fragment, rather than exiting entirely. Changing the back x2 exit flow from finishAndRemoveTask to finishAffinity solved my problem. Why did this work?
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).
finishAndRemoveTask() Finishes all activities in this task and removes it from the recent tasks list.
Explanation. Generally, every activity is having its UI(Layout). But if a developer wants to create an activity without UI, he can do it.
You must call the second activity using the startActivityForResult method. In your second activity, when it is finished, you can execute the setResult method where basically you put the result information. Then, on your first activity, you override the onActivityResult method.
In Android, all activities are managed in a Task Stack. The affinity is used to group activities under a specific task stack. In general, the affinity indicates in which task an activity prefers or belongs to. Once you understand how the stack works, the meaning of finishAffinity() and finishAndRemoveTask() is pretty simple.
finishAffinity()
Finish this activity as well as all activities immediately below it in the current task that have the same affinity.
finishAndRemoveTask()
Call this when your activity is done and should be closed and the task should be completely removed as a part of finishing the root activity of the task.
A good demonstration of Activity's launchMode: standard, singleTop, singleTask and singleInstance is available here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With