Fix MixedDeviceOwnerTest test failure

NullPointerException was thrown while running the test because
the top activity of the most recent task is null. This is a
regression caused by commit 1ff574d.

It happens when adding a recent task because of resuming the next
activity while the top-most activity finishes (the activities are
in two different Tasks). The finishing task still has the higher
z-ordering in the WM hierarchy which therefore was remained be the
most recent task.

The finishing task should be excluded and the most recent task
should be the one that is resumed.

Bug: 326367294
Test: atest RecentTasksTest
Test: atest MixedDeviceOwnerTest
(cherry picked from https://googleplex-android-review.googlesource.com/q/commit:5f1e492e159fd19b567ba5b62d3e2f2e5f733425)
Merged-In: Iba8a2004a58a4d440a0c62c59ae89b5e4ca1253c
Change-Id: Iba8a2004a58a4d440a0c62c59ae89b5e4ca1253c
diff --git a/services/core/java/com/android/server/wm/RecentTasks.java b/services/core/java/com/android/server/wm/RecentTasks.java
index dd14642..4a09e8d 100644
--- a/services/core/java/com/android/server/wm/RecentTasks.java
+++ b/services/core/java/com/android/server/wm/RecentTasks.java
@@ -1258,6 +1258,11 @@
                 continue;
             }
 
+            if (otherTask.topRunningActivity() == null) {
+                // Skip if there's no running activity in the Task.
+                continue;
+            }
+
             // Stop searching if the task has higher z-ordering, or increase the index and
             // continue the search.
             if (task.compareTo(otherTask) > 0) {
diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
index f7c253d..bfa191e 100644
--- a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
@@ -1210,9 +1210,11 @@
     @Test
     public void addTask_tasksAreAddedAccordingToZOrder() {
         final Task firstTask = new TaskBuilder(mSupervisor).setTaskId(1)
-                .setWindowingMode(WINDOWING_MODE_FREEFORM).build();
+                .setWindowingMode(WINDOWING_MODE_FREEFORM)
+                .setCreateActivity(true).build();
         final Task secondTask = new TaskBuilder(mSupervisor).setTaskId(2)
-                .setWindowingMode(WINDOWING_MODE_FREEFORM).build();
+                .setWindowingMode(WINDOWING_MODE_FREEFORM)
+                .setCreateActivity(true).build();
 
         assertEquals(-1, firstTask.compareTo(secondTask));