Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: finishAffinity() vs finishAndRemoveTask()

Tags:

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?

like image 255
Josh Beckwith Avatar asked Aug 16 '17 02:08

Josh Beckwith


People also ask

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).

What is finishAndRemoveTask?

finishAndRemoveTask() Finishes all activities in this task and removes it from the recent tasks list.

Can we create activity without UI in Android?

Explanation. Generally, every activity is having its UI(Layout). But if a developer wants to create an activity without UI, he can do it.

How do you get a response from an activity in Android?

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.


1 Answers

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.

enter image description here

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.

like image 88
Prokash Sarkar Avatar answered Sep 22 '22 18:09

Prokash Sarkar