Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android clear / finish previous activities except one

In android I have the following path:

Activity 1 -> Activity 2 -> Activity 3 -> ... Activity N -> press button ...

When the button is pressed I want to Clear/Finish ALL activities from Activity 2 until N and then go to Acitivy X. In other words I want to finish all activities down to the initial One and then move to another.

If I use the flags:

CLEAR_TOP, CLEAR_TASK, NEW_TASK etc

theoritically it would finish ALL previous activities with the initial one. Is there any way to keep the initial one alive and move to activity X?

like image 544
Panos Avatar asked Oct 21 '22 07:10

Panos


1 Answers

I'm not sure I understand the question. Or rather, the reason for not being able to use FLAG_ACTIVITY_CLEAR_TOP.

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

For example, consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.

If I understand correctly, that's exactly what you want. In particular for,

Activity 1 -> Activity 2 -> Activity 3 -> ... Activity N -> press button ...

Launching an Intent with Activity2.class and flags FLAG_ACTIVITY_CLEAR_TOP | FLAG_ACTIVITY_SINGLE_TOP would go back to the existing instance of Activity2 (instead of creating a new one) and deliver the new intent in onNewIntent(). You just need to add an extra to this intent, so that this method will know that it's supposed to call ActivityX afterwards.

That is, unless I'm missing something. :)

like image 59
matiash Avatar answered Oct 29 '22 18:10

matiash