androidandroid-activityactivity-stack

how to destroy all the activites except the latest 3?


I have activities like A->B->C->D. How can I close the A activity if I have 4 activities on my stack? Also later when I open activity E i want B to be closed aswell, so I want to have C->D->E only.


Solution

  • There is no such as a direct way to manage activities number in stack. So far I know that stack is big as much as available memory.

    Also consider LaunchMode and whether activities are in the same task or not.

    So, you might implement your own Activity manager to finish un-wanted activities.

    Here is briefly how I see the solution:

    1. Create a model to store activity, its index in stack, date ..i.e. ActivityItem
    2. Create an empty List of ActivityItem in your custom Application. To avoid memory leak, use WeakReference. create a public setter adActivity to add and manage activities
    3. Better approach to create activity base class and reuse it as superClass wherever you want to manage count of running activities. instead of repeating same implementation for each different activity.
    4. OnCreate in your base Activity call adActivity and pass current activity.
    5. adActivity job is firstly clean the list of destroyed activities. thanks WeakReference. Then manually kill older activities before last 3 items in your list. It's not easy as it looks.. for example: SingleInstance and rotation will make it challenge to achieve this :-)

    that is it.

    Good luck,'.