Finish more than one Activity at once.
Today I had the task to create some kind of navigation for different screens. In the screens the user could press next, which brings her to the next screen. Back, which brings her to the previous screen in it’s left state and cancel, which cancels brings her to the initial screen. Looking at the following image will make this more clear:
The problem hereby is the cancel action, where the user has to get back to the initial activity, nevertheless in which activity she currently is. I had some ideas, discussed it also with my colleague and came up with something like:
- Create some kind of state machine in the
Initial Activitywhich takes care which activity comes next and what happens when the user presses back or cancel.
- Start every Activity with
startActivityForResult()and if the user presses cancel the current Activity finishes itself with a specific result code, and so on.
Since I wasn’t happy with any of those ideas, I did some research and found a pretty simple solution.
Since API level 16 there is the Activity method
finishAffinity()1 which is the same as finish, but just don’t finishes the calling Activity it also finishes every Activity below with the same affinity.
But since all Activities have the same affinity by default in one application, the affinity for the specific Activities has to be defined.
This can be achieved with the
android:taskAffinity2 inside the
AndroidManifest.xml, by just defining it as the following:
1 2 3
As mentioned above this has been introduced with API 16, however there is a corresponding
This just calls finish on API levels < 16, so this should not work there, but since our app is
minSdkVersion 17 I don’t have to worry about it and it works as intended.
I made a small example app, which shows the working navigation:
This was a pretty easy solution, compared with the first ideas.