Search code examples
androidandroid-activityactivity-stack

android: Moving through activities without popping them


I have the following I wish to achieve:

Activity A -> Activity B

Activity B -> Activity A

On paper it sounds like the same thing as just hitting the back button. Problem is, I don't want Activity B to be popped.

I need something along the lines of moveTaskToBackground but for a single activity. That way when I go back to it from A again, it can resume.

To give you some context, Activity A is a list of items. Activity B displays information about the item and plays a song attached to it. While going back from B to A, I want that song to keep playing, that way if the person hits the same option in A they just resume the activity. Otherwise kill that activity and start a new one with the new details and play the new song.


Solution

  • You need to look into ActivityGroup and LocalActivityManager. TabActivity (as suggested in other answer) actually extends ActivityGroup.

    Here is a quick example to get you started:

    Use this to start activity A:

    LocalActivityManager manager =  getLocalActivityManager();  
    
    //A_ID == 1
    Window activityWindow = manager.startActivity(A_ID, intent_activityA); 
    setContentView(activityWindow.getDecorView());
    

    or this to start activity B:

    //B_ID == 2
    Window activityWindow = manager.startActivity(B_ID, intent_activityB);
    setContentView(activityWindow.getDecorView());
    

    Activities are cached and associated with specified IDs. If you invoke startActivity with the same id several times, then cached activity is actually used (not always, depends on intents you use). You can easily remove any activity from cache if you need. Look into LocalActivityManager for more details.