Switching back to previous task in android

724 views Asked by At

I have three activities A, B, and C. As expected when C is changed to pip (picture in picture) mode, it is separated out as a new task. When back pressed is pressed on Activity C, it will be finished and the user will be sent to the android system home screen. I want the user to shift to the activity from where Activity C was called; including the whole back stack of that task.

The experience can be understood like this:

Task1: A->B->C

user presses home button, c is now shifted to pip mode

Task 1: A->B

Task 2: C

Now C is sent to full screen and back button is pressed.

Task 1: A->B

Task 2:

The user has been sent to the android home screen. I want the user to be shifted to Activity B. Basically, it means, I want to get access to the previous running task (Task1) after the current activity in another task (Task2) is over.

2

There are 2 answers

1
return 0 On

In your manifest, add ActivityB as Parent activity to C

AndroidManifest.xml

<application ....>
<activity android:name="package.ActivityB"/>
<activity android:name="package.ActivityC"
          android:parentActivityName="package.ActivityB"/>
</application>

0
pulkit garg On

Basically, this needs to be handled by performing two workarounds.

  1. declare Activity C (pip activity) as android:launchMode="singleInstance" and define a task affinity for it: android:taskAffinity=":pip".
  2. when Activity C is finished(), call this function:
fun navToMainTask(appContext: Context){
        val activityManager =
            (appContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager)
        val appTasks = activityManager.appTasks
        for (task in appTasks) {
            val baseIntent = task.taskInfo.baseIntent
            val categories = baseIntent.categories
            if (categories != null && categories.contains(Intent.CATEGORY_LAUNCHER)) {
                task.moveToFront()
                return
            }
        }
    }

By assigning task affinity, we have asked the pip activity to launch within our app's process. Hence, activityManager.appTasks will return us two tasks:

a) Task1: A->B

b) Task2: C

Since Activity A is the Main Activity by which our app is launched, it would have been categorized as "launcher" in the manifest file.

The for loop will check for all tasks of the application and will bring the task having launcher activity to the front.

Hence, when Activity C is destroyed, Task1 will be moved to the front, and Activity B will be visible to the user.