Ensure consistent stack behind PIP when going to/from fullscreen.

- When a fullscreen activity enters PIP, we were previously always
  bringing the home stack forward due to the return type being set
  to HOME_ACTIVITY_TYPE, causing the home screen to be visible if
  expanding PIP over a fullscreen activity and going back into PIP
  immediately.  This CL instead updates the return-to type to
  reflect the stack that was currently open before the pinned task
  was made fullscreen again to ensure that it is consistent when
  entering PIP again.

Test: android.server.cts.ActivityManagerPinnedStackTests
Test: #testPipUnPipOverHome
Test: #testPipUnPipOverApp

Change-Id: Id5dd7db1f5a8040ff21190cc347eb6aae5893006
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
index 8bb0e1a..282ec50 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/am/ActivityStackSupervisor.java
@@ -2120,6 +2120,14 @@
             final int size = tasks.size();
             if (onTop) {
                 for (int i = 0; i < size; i++) {
+                    final TaskRecord task = tasks.get(i);
+                    if (fromStackId == PINNED_STACK_ID) {
+                        // Update the return-to to reflect where the pinned stack task was moved
+                        // from so that we retain the stack that was previously visible if the
+                        // pinned stack is recreated. See moveActivityToPinnedStackLocked().
+                        task.setTaskToReturnTo(getFocusedStack().getStackId() == HOME_STACK_ID
+                                ? HOME_ACTIVITY_TYPE : APPLICATION_ACTIVITY_TYPE);
+                    }
                     moveTaskToStackLocked(tasks.get(i).taskId,
                             FULLSCREEN_WORKSPACE_STACK_ID, onTop, onTop /*forceFocus*/,
                             "moveTasksToFullscreenStack", ANIMATE, DEFER_RESUME);