Start process of next activity with top priority in advance

In common cases, to resume the next activity we need to wait for the
current one to be paused. Since starting a process for activity is
asynchronous, if we already know the process of next activity has not
started yet, we can start the process earlier so the time waiting for
the pause to complete can be saved.

Also if the launching activity is going to be the top app, we can set
the top schedule group right after its process is started so the start
time before actually launching the activity can be improved.

Although before the current activity is paused, the next top activity
may still change and results some empty processes. That should not be
a common case and the process is still useful when going back the stack,
and the empty background processes are easier to be reclaimed.

Bug: 123043091
Test: AppLaunchTest
Test: Launch calculator from launcher, the event log am_proc_start will
      show "pre-top-activity".
Test: Cold launch a top activity, the system log should not show
      "not expected top priority".
Test: Use startActivities to start serveral activities in a sequence.
      Check "adb shell cat /proc/$pid/task/$pid/cgroup" for each process.
      Only the last one has top-app, others are background.

Change-Id: I9601b66e7cc0855fd7c2b573ded31fcf8d0711ae
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index f76d0eb..d4b49aa 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -5631,6 +5631,24 @@
         mH.sendMessage(m);
     }
 
+    void startProcessAsync(ActivityRecord activity, boolean knownToBeDead, boolean isTop,
+            String hostingType) {
+        try {
+            if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
+                Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
+                        + activity.processName);
+            }
+            // Post message to start process to avoid possible deadlock of calling into AMS with the
+            // ATMS lock held.
+            final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
+                    mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
+                    isTop, hostingType, activity.intent.getComponent());
+            mH.sendMessage(m);
+        } finally {
+            Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
+        }
+    }
+
     void setBooting(boolean booting) {
         mAmInternal.setBooting(booting);
     }