Android switching between tasks

987 Views Asked by At

I'm trying to find a way to switch between tasks in android.

Let's say I have Activity A, B, C, D.

Activity A and B are in one task(affinity)

While C and D are in another task.

This is the manifest code of C activity which creates a new task.

 <activity
        android:name=".CActivity"
        android:launchMode="singleTask"
        android:taskAffinity="com.new" />

A, B created in one task and C, D created in another task. Now, we need to just switch from D to B without creating a new instance of B. Also could able to switch from A to D without creating a new instance of D.

TASK 1: A > B TASK 2: C > D

Edit: These two stacks are from the same app. The reason I'm using two is one is my normal app and another stack is for the video call feature in my app. So that user can do video call & minimize the window and use the normal flow of the app.

2

There are 2 best solutions below

5
On

I think you should set flag FLAG_ACTIVITY_REORDER_TO_FRONT on Activity B and Activity D. If those activities were previously created, they will be brought to front from the activities stack.

2
On

I assume that you don't want to use Intent because whenever you use Intent for moving to activity A pressing Back key will move to the previous activity (activity C). In this case I would suggest you to include FLAG_ACTIVITY_CLEAR_TOP flag. It will destroy all the previous activity and let you to move to Activity A.

Intent a = new Intent(this,A.class);
     a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
     startActivity(a);

Alternatively, you can try the FLAG_ACTIVITY_REORDER_TO_FRONT flag instead, which will move to activity A without clearing any activity.

Or if you dont want to create new instance then

Set launchMode of Activities to singleInstance in AndroidManifest.xml

Hope this helps.

or

1.) Make B a "SingleTask" activity. You can do this in the Android Manifest. To be brief, this means that only one 'instance' of B will ever exist within this Task. If B is already running when it's called then it will simply be brought to the front. This is how you do that.

<activity
        android:name=".ui.MyActivity"
        android:launchMode="singleTask"/>

But you don't want to just bring B to the front. You want to 'fall back' to B so that your stack looks like

A--> B

2.) Add this flag to your intent that 'starts' B. This ensures that C and D are removed.

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

Now when 'D' calls new Intent to B, B will be resumed and C and D will be removed. B will not be recreated, it will only call onNewIntent.

OR

You start Activities Using StartActivityForResult()

And based on conditions You set ResultCodes in Activities.. Something like this..

GO_TO_ACT_A=1; GO_TO_ACT_B=2;

And in all Activies onActivityResultMethod check the result code..

if(resultCode==GO_TO_ACT_A){
    finish(); //Assuming curently you are in Activity C and wanna go to Activity A
}