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?
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.
Finish this activity as well as all activities immediately below it in the current task that have the same affinity.
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.