Merge "Refactored RemoteFillService logic into a common class."
diff --git a/Android.bp b/Android.bp
index b715b73..e669307 100644
--- a/Android.bp
+++ b/Android.bp
@@ -1567,6 +1567,10 @@
 droidstubs {
     name: "hiddenapi-mappings",
     defaults: ["metalava-api-stubs-default"],
+    srcs: [
+        ":openjdk_java_files",
+        ":non_openjdk_java_files",
+    ],
     arg_files: [
         "core/res/AndroidManifest.xml",
     ],
diff --git a/apct-tests/perftests/core/src/android/util/ArraySetPerfTest.java b/apct-tests/perftests/core/src/android/util/ArraySetPerfTest.java
new file mode 100644
index 0000000..0c1f289
--- /dev/null
+++ b/apct-tests/perftests/core/src/android/util/ArraySetPerfTest.java
@@ -0,0 +1,212 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.util;
+
+import android.perftests.utils.BenchmarkState;
+import android.perftests.utils.PerfStatusReporter;
+import android.support.test.filters.LargeTest;
+import android.support.test.runner.AndroidJUnit4;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+
+import java.util.function.Predicate;
+
+@RunWith(AndroidJUnit4.class)
+@LargeTest
+public class ArraySetPerfTest {
+    private static final int NUM_ITERATIONS = 100;
+    private static final int SET_SIZE_SMALL = 10;
+    private static final int SET_SIZE_LARGE = 50;
+
+    @Rule
+    public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
+
+    @Test
+    public void testValueAt_InBounds() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        ArraySet<Integer> set = new ArraySet<>();
+        set.add(0);
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                set.valueAt(0);
+            }
+        }
+    }
+
+    @Test
+    public void testValueAt_OutOfBounds_Negative() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        ArraySet<Integer> set = new ArraySet<>();
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                try {
+                    set.valueAt(-1);
+                } catch (ArrayIndexOutOfBoundsException expected) {
+                    // expected
+                }
+            }
+        }
+    }
+
+    /**
+     * Tests the case where ArraySet could index into its array even though the index is out of
+     * bounds.
+     */
+    @Test
+    public void testValueAt_OutOfBounds_EdgeCase() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        ArraySet<Integer> set = new ArraySet<>();
+        set.add(0);
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                try {
+                    set.valueAt(1);
+                } catch (ArrayIndexOutOfBoundsException expected) {
+                    // expected
+                }
+            }
+        }
+    }
+
+    /**
+     * This is the same code as testRemoveIf_Small_* without the removeIf in order to measure
+     * the performance of the rest of the code in the loop.
+     */
+    @Test
+    public void testRemoveIf_Small_Base() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        Predicate<Integer> predicate = (i) -> i % 2 == 0;
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                ArraySet<Integer> set = new ArraySet<>();
+                for (int j = 0; j < SET_SIZE_SMALL; ++j) {
+                    set.add(j);
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testRemoveIf_Small_RemoveNothing() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        Predicate<Integer> predicate = (i) -> false;
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                ArraySet<Integer> set = new ArraySet<>();
+                for (int j = 0; j < SET_SIZE_SMALL; ++j) {
+                    set.add(j);
+                }
+                set.removeIf(predicate);
+            }
+        }
+    }
+
+    @Test
+    public void testRemoveIf_Small_RemoveAll() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        Predicate<Integer> predicate = (i) -> true;
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                ArraySet<Integer> set = new ArraySet<>();
+                for (int j = 0; j < SET_SIZE_SMALL; j++) {
+                    set.add(j);
+                }
+                set.removeIf(predicate);
+            }
+        }
+    }
+
+    @Test
+    public void testRemoveIf_Small_RemoveHalf() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        Predicate<Integer> predicate = (i) -> i % 2 == 0;
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                ArraySet<Integer> set = new ArraySet<>();
+                for (int j = 0; j < SET_SIZE_SMALL; ++j) {
+                    set.add(j);
+                }
+                set.removeIf(predicate);
+            }
+        }
+    }
+
+    /**
+     * This is the same code as testRemoveIf_Large_* without the removeIf in order to measure
+     * the performance of the rest of the code in the loop.
+     */
+    @Test
+    public void testRemoveIf_Large_Base() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        Predicate<Integer> predicate = (i) -> i % 2 == 0;
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                ArraySet<Integer> set = new ArraySet<>();
+                for (int j = 0; j < SET_SIZE_LARGE; ++j) {
+                    set.add(j);
+                }
+            }
+        }
+    }
+
+    @Test
+    public void testRemoveIf_Large_RemoveNothing() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        Predicate<Integer> predicate = (i) -> false;
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                ArraySet<Integer> set = new ArraySet<>();
+                for (int j = 0; j < SET_SIZE_LARGE; ++j) {
+                    set.add(j);
+                }
+                set.removeIf(predicate);
+            }
+        }
+    }
+
+    @Test
+    public void testRemoveIf_Large_RemoveAll() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        Predicate<Integer> predicate = (i) -> true;
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                ArraySet<Integer> set = new ArraySet<>();
+                for (int j = 0; j < SET_SIZE_LARGE; ++j) {
+                    set.add(j);
+                }
+                set.removeIf(predicate);
+            }
+        }
+    }
+
+    @Test
+    public void testRemoveIf_Large_RemoveHalf() {
+        BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
+        Predicate<Integer> predicate = (i) -> i % 2 == 0;
+        while (state.keepRunning()) {
+            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                ArraySet<Integer> set = new ArraySet<>();
+                for (int j = 0; j < SET_SIZE_LARGE; ++j) {
+                    set.add(j);
+                }
+                set.removeIf(predicate);
+            }
+        }
+    }
+}
diff --git a/api/current.txt b/api/current.txt
index 5ab3f6a..3deb15a 100755
--- a/api/current.txt
+++ b/api/current.txt
@@ -13434,6 +13434,7 @@
     method public boolean clipRect(float, float, float, float);
     method public boolean clipRect(int, int, int, int);
     method public void concat(android.graphics.Matrix);
+    method public void disableZ();
     method public void drawARGB(int, int, int, int);
     method public void drawArc(android.graphics.RectF, float, float, boolean, android.graphics.Paint);
     method public void drawArc(float, float, float, float, float, float, boolean, android.graphics.Paint);
@@ -13468,6 +13469,7 @@
     method public void drawRect(android.graphics.RectF, android.graphics.Paint);
     method public void drawRect(android.graphics.Rect, android.graphics.Paint);
     method public void drawRect(float, float, float, float, android.graphics.Paint);
+    method public void drawRenderNode(android.graphics.RenderNode);
     method public void drawRoundRect(android.graphics.RectF, float, float, android.graphics.Paint);
     method public void drawRoundRect(float, float, float, float, float, float, android.graphics.Paint);
     method public void drawText(char[], int, int, float, float, android.graphics.Paint);
@@ -13479,6 +13481,7 @@
     method public void drawTextRun(char[], int, int, int, int, float, float, boolean, android.graphics.Paint);
     method public void drawTextRun(java.lang.CharSequence, int, int, int, int, float, float, boolean, android.graphics.Paint);
     method public void drawVertices(android.graphics.Canvas.VertexMode, int, float[], int, float[], int, int[], int, short[], int, int, android.graphics.Paint);
+    method public void enableZ();
     method public boolean getClipBounds(android.graphics.Rect);
     method public final android.graphics.Rect getClipBounds();
     method public int getDensity();
@@ -14468,6 +14471,9 @@
     ctor public RadialGradient(float, float, float, int, int, android.graphics.Shader.TileMode);
   }
 
+  public final class RecordingCanvas extends android.graphics.Canvas {
+  }
+
   public final class Rect implements android.os.Parcelable {
     ctor public Rect();
     ctor public Rect(int, int, int, int);
@@ -14604,6 +14610,77 @@
     method public final boolean next(android.graphics.Rect);
   }
 
+  public class RenderNode {
+    method public int computeApproximateMemoryUsage();
+    method public static android.graphics.RenderNode create(java.lang.String);
+    method public void discardDisplayList();
+    method public void endRecording();
+    method public float getAlpha();
+    method public int getAmbientShadowColor();
+    method public int getBottom();
+    method public float getCameraDistance();
+    method public boolean getClipToOutline();
+    method public float getElevation();
+    method public int getHeight();
+    method public void getInverseMatrix(android.graphics.Matrix);
+    method public int getLeft();
+    method public void getMatrix(android.graphics.Matrix);
+    method public float getPivotX();
+    method public float getPivotY();
+    method public int getRight();
+    method public float getRotation();
+    method public float getRotationX();
+    method public float getRotationY();
+    method public float getScaleX();
+    method public float getScaleY();
+    method public int getSpotShadowColor();
+    method public int getTop();
+    method public float getTranslationX();
+    method public float getTranslationY();
+    method public float getTranslationZ();
+    method public int getWidth();
+    method public boolean hasDisplayList();
+    method public boolean hasIdentityMatrix();
+    method public boolean hasOverlappingRendering();
+    method public boolean hasShadow();
+    method public boolean isForceDarkAllowed();
+    method public boolean isPivotExplicitlySet();
+    method public boolean offsetLeftAndRight(int);
+    method public boolean offsetTopAndBottom(int);
+    method public boolean resetPivot();
+    method public boolean setAlpha(float);
+    method public boolean setAmbientShadowColor(int);
+    method public boolean setBottom(int);
+    method public boolean setCameraDistance(float);
+    method public boolean setClipBounds(android.graphics.Rect);
+    method public boolean setClipToBounds(boolean);
+    method public boolean setClipToOutline(boolean);
+    method public boolean setElevation(float);
+    method public boolean setForceDarkAllowed(boolean);
+    method public boolean setHasOverlappingRendering(boolean);
+    method public boolean setLeft(int);
+    method public boolean setLeftTopRightBottom(int, int, int, int);
+    method public boolean setOutline(android.graphics.Outline);
+    method public boolean setPivotX(float);
+    method public boolean setPivotY(float);
+    method public boolean setProjectBackwards(boolean);
+    method public boolean setProjectionReceiver(boolean);
+    method public boolean setRight(int);
+    method public boolean setRotation(float);
+    method public boolean setRotationX(float);
+    method public boolean setRotationY(float);
+    method public boolean setScaleX(float);
+    method public boolean setScaleY(float);
+    method public boolean setSpotShadowColor(int);
+    method public boolean setTop(int);
+    method public boolean setTranslationX(float);
+    method public boolean setTranslationY(float);
+    method public boolean setTranslationZ(float);
+    method public boolean setUseCompositingLayer(boolean, android.graphics.Paint);
+    method public android.graphics.RecordingCanvas startRecording(int, int);
+    method public android.graphics.RecordingCanvas startRecording();
+  }
+
   public class Shader {
     ctor public deprecated Shader();
     method public boolean getLocalMatrix(android.graphics.Matrix);
@@ -14694,8 +14771,7 @@
     ctor public Typeface.CustomFallbackBuilder(android.graphics.fonts.FontFamily);
     method public android.graphics.Typeface build();
     method public android.graphics.Typeface.CustomFallbackBuilder setFallback(java.lang.String);
-    method public android.graphics.Typeface.CustomFallbackBuilder setItalic(boolean);
-    method public android.graphics.Typeface.CustomFallbackBuilder setWeight(int);
+    method public android.graphics.Typeface.CustomFallbackBuilder setStyle(android.graphics.fonts.FontStyle);
   }
 
   public class Xfermode {
@@ -15340,9 +15416,8 @@
     method public java.nio.ByteBuffer getBuffer();
     method public java.io.File getFile();
     method public android.os.LocaleList getLocaleList();
-    method public int getSlant();
+    method public android.graphics.fonts.FontStyle getStyle();
     method public int getTtcIndex();
-    method public int getWeight();
   }
 
   public static class Font.Builder {
@@ -22714,6 +22789,7 @@
     field public static final int ENCODING_AC3 = 5; // 0x5
     field public static final int ENCODING_AC4 = 17; // 0x11
     field public static final int ENCODING_DEFAULT = 1; // 0x1
+    field public static final int ENCODING_DOLBY_MAT = 19; // 0x13
     field public static final int ENCODING_DOLBY_TRUEHD = 14; // 0xe
     field public static final int ENCODING_DTS = 7; // 0x7
     field public static final int ENCODING_DTS_HD = 8; // 0x8
@@ -33189,6 +33265,7 @@
     field public static java.lang.String DIRECTORY_PICTURES;
     field public static java.lang.String DIRECTORY_PODCASTS;
     field public static java.lang.String DIRECTORY_RINGTONES;
+    field public static java.lang.String DIRECTORY_SCREENSHOTS;
     field public static final java.lang.String MEDIA_BAD_REMOVAL = "bad_removal";
     field public static final java.lang.String MEDIA_CHECKING = "checking";
     field public static final java.lang.String MEDIA_EJECTING = "ejecting";
@@ -34040,6 +34117,7 @@
     field public static final java.lang.String DISALLOW_INSTALL_APPS = "no_install_apps";
     field public static final java.lang.String DISALLOW_INSTALL_UNKNOWN_SOURCES = "no_install_unknown_sources";
     field public static final java.lang.String DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY = "no_install_unknown_sources_globally";
+    field public static final java.lang.String DISALLOW_INTELLIGENCE_CAPTURE = "no_intelligence_capture";
     field public static final java.lang.String DISALLOW_MODIFY_ACCOUNTS = "no_modify_accounts";
     field public static final java.lang.String DISALLOW_MOUNT_PHYSICAL_MEDIA = "no_physical_media";
     field public static final java.lang.String DISALLOW_NETWORK_RESET = "no_network_reset";
@@ -36917,12 +36995,15 @@
 
   public final class MediaStore {
     ctor public MediaStore();
+    method public static android.net.Uri createPending(android.content.Context, android.provider.MediaStore.PendingParams);
     method public static java.util.Set<java.lang.String> getAllVolumeNames(android.content.Context);
     method public static android.net.Uri getDocumentUri(android.content.Context, android.net.Uri);
     method public static android.net.Uri getMediaScannerUri();
     method public static android.net.Uri getMediaUri(android.content.Context, android.net.Uri);
     method public static java.lang.String getVersion(android.content.Context);
     method public static java.lang.String getVolumeName(android.net.Uri);
+    method public static android.provider.MediaStore.PendingSession openPending(android.content.Context, android.net.Uri);
+    method public static android.net.Uri setIncludePending(android.net.Uri);
     field public static final java.lang.String ACTION_IMAGE_CAPTURE = "android.media.action.IMAGE_CAPTURE";
     field public static final java.lang.String ACTION_IMAGE_CAPTURE_SECURE = "android.media.action.IMAGE_CAPTURE_SECURE";
     field public static final java.lang.String ACTION_REVIEW = "android.provider.action.REVIEW";
@@ -37180,12 +37261,29 @@
     field public static final java.lang.String DISPLAY_NAME = "_display_name";
     field public static final java.lang.String HASH = "_hash";
     field public static final java.lang.String HEIGHT = "height";
+    field public static final java.lang.String IS_PENDING = "is_pending";
     field public static final java.lang.String MIME_TYPE = "mime_type";
+    field public static final java.lang.String OWNER_PACKAGE_NAME = "owner_package_name";
     field public static final java.lang.String SIZE = "_size";
     field public static final java.lang.String TITLE = "title";
     field public static final java.lang.String WIDTH = "width";
   }
 
+  public static class MediaStore.PendingParams {
+    ctor public MediaStore.PendingParams(android.net.Uri, java.lang.String, java.lang.String);
+    method public void setPrimaryDirectory(java.lang.String);
+    method public void setSecondaryDirectory(java.lang.String);
+  }
+
+  public static class MediaStore.PendingSession implements java.lang.AutoCloseable {
+    method public void abandon();
+    method public void close();
+    method public void notifyProgress(int);
+    method public android.os.ParcelFileDescriptor open() throws java.io.FileNotFoundException;
+    method public java.io.OutputStream openOutputStream() throws java.io.FileNotFoundException;
+    method public android.net.Uri publish();
+  }
+
   public static final class MediaStore.Video {
     ctor public MediaStore.Video();
     method public static android.database.Cursor query(android.content.ContentResolver, android.net.Uri, java.lang.String[]);
@@ -37270,6 +37368,7 @@
     field public static final java.lang.String ACTION_APPLICATION_SETTINGS = "android.settings.APPLICATION_SETTINGS";
     field public static final java.lang.String ACTION_APP_NOTIFICATION_SETTINGS = "android.settings.APP_NOTIFICATION_SETTINGS";
     field public static final java.lang.String ACTION_APP_SEARCH_SETTINGS = "android.settings.APP_SEARCH_SETTINGS";
+    field public static final java.lang.String ACTION_APP_USAGE_SETTINGS = "android.settings.action.APP_USAGE_SETTINGS";
     field public static final java.lang.String ACTION_BATTERY_SAVER_SETTINGS = "android.settings.BATTERY_SAVER_SETTINGS";
     field public static final java.lang.String ACTION_BLUETOOTH_SETTINGS = "android.settings.BLUETOOTH_SETTINGS";
     field public static final java.lang.String ACTION_CAPTIONING_SETTINGS = "android.settings.CAPTIONING_SETTINGS";
@@ -42295,6 +42394,7 @@
     method public java.lang.String getVoiceMailNumber(android.telecom.PhoneAccountHandle);
     method public boolean handleMmi(java.lang.String);
     method public boolean handleMmi(java.lang.String, android.telecom.PhoneAccountHandle);
+    method public boolean isDefaultCallScreeningApp(android.content.ComponentName);
     method public boolean isInCall();
     method public boolean isInManagedCall();
     method public boolean isIncomingCallPermitted(android.telecom.PhoneAccountHandle);
@@ -42303,12 +42403,14 @@
     method public boolean isVoiceMailNumber(android.telecom.PhoneAccountHandle, java.lang.String);
     method public void placeCall(android.net.Uri, android.os.Bundle);
     method public void registerPhoneAccount(android.telecom.PhoneAccount);
+    method public void requestChangeDefaultCallScreeningApp(android.content.ComponentName);
     method public void showInCallScreen(boolean);
     method public void silenceRinger();
     method public void unregisterPhoneAccount(android.telecom.PhoneAccountHandle);
     field public static final java.lang.String ACTION_CHANGE_DEFAULT_DIALER = "android.telecom.action.CHANGE_DEFAULT_DIALER";
     field public static final java.lang.String ACTION_CHANGE_PHONE_ACCOUNTS = "android.telecom.action.CHANGE_PHONE_ACCOUNTS";
     field public static final java.lang.String ACTION_CONFIGURE_PHONE_ACCOUNT = "android.telecom.action.CONFIGURE_PHONE_ACCOUNT";
+    field public static final java.lang.String ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED = "android.telecom.action.DEFAULT_CALL_SCREENING_APP_CHANGED";
     field public static final java.lang.String ACTION_DEFAULT_DIALER_CHANGED = "android.telecom.action.DEFAULT_DIALER_CHANGED";
     field public static final deprecated java.lang.String ACTION_INCOMING_CALL = "android.telecom.action.INCOMING_CALL";
     field public static final java.lang.String ACTION_PHONE_ACCOUNT_REGISTERED = "android.telecom.action.PHONE_ACCOUNT_REGISTERED";
@@ -42325,9 +42427,11 @@
     field public static final java.lang.String EXTRA_CALL_NETWORK_TYPE = "android.telecom.extra.CALL_NETWORK_TYPE";
     field public static final java.lang.String EXTRA_CALL_SUBJECT = "android.telecom.extra.CALL_SUBJECT";
     field public static final java.lang.String EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME = "android.telecom.extra.CHANGE_DEFAULT_DIALER_PACKAGE_NAME";
+    field public static final java.lang.String EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME = "android.telecom.extra.DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME";
     field public static final java.lang.String EXTRA_INCOMING_CALL_ADDRESS = "android.telecom.extra.INCOMING_CALL_ADDRESS";
     field public static final java.lang.String EXTRA_INCOMING_CALL_EXTRAS = "android.telecom.extra.INCOMING_CALL_EXTRAS";
     field public static final java.lang.String EXTRA_INCOMING_VIDEO_STATE = "android.telecom.extra.INCOMING_VIDEO_STATE";
+    field public static final java.lang.String EXTRA_IS_DEFAULT_CALL_SCREENING_APP = "android.telecom.extra.IS_DEFAULT_CALL_SCREENING_APP";
     field public static final java.lang.String EXTRA_NOTIFICATION_COUNT = "android.telecom.extra.NOTIFICATION_COUNT";
     field public static final java.lang.String EXTRA_NOTIFICATION_PHONE_NUMBER = "android.telecom.extra.NOTIFICATION_PHONE_NUMBER";
     field public static final java.lang.String EXTRA_OUTGOING_CALL_EXTRAS = "android.telecom.extra.OUTGOING_CALL_EXTRAS";
@@ -48356,6 +48460,7 @@
     ctor public TouchDelegate(android.graphics.Rect, android.view.View);
     method public android.view.accessibility.AccessibilityNodeInfo.TouchDelegateInfo getTouchDelegateInfo();
     method public boolean onTouchEvent(android.view.MotionEvent);
+    method public boolean onTouchExplorationHoverEvent(android.view.MotionEvent);
     field public static final int ABOVE = 1; // 0x1
     field public static final int BELOW = 2; // 0x2
     field public static final int TO_LEFT = 4; // 0x4
@@ -51457,6 +51562,17 @@
 
 }
 
+package android.view.intelligence {
+
+  public final class IntelligenceManager {
+    method public void disableContentCapture();
+    method public android.content.ComponentName getIntelligenceServiceComponentName();
+    method public boolean isContentCaptureEnabled();
+    field public static final int FLAG_USER_INPUT = 1; // 0x1
+  }
+
+}
+
 package android.view.textclassifier {
 
   public final class ConversationActions implements android.os.Parcelable {
@@ -55053,6 +55169,9 @@
     method public android.os.LocaleList getTextLocales();
     method public android.text.PrecomputedText.Params getTextMetricsParams();
     method public float getTextScaleX();
+    method public android.graphics.drawable.Drawable getTextSelectHandle();
+    method public android.graphics.drawable.Drawable getTextSelectHandleLeft();
+    method public android.graphics.drawable.Drawable getTextSelectHandleRight();
     method public float getTextSize();
     method public int getTotalPaddingBottom();
     method public int getTotalPaddingEnd();
@@ -55181,6 +55300,12 @@
     method public void setTextLocales(android.os.LocaleList);
     method public void setTextMetricsParams(android.text.PrecomputedText.Params);
     method public void setTextScaleX(float);
+    method public void setTextSelectHandle(android.graphics.drawable.Drawable);
+    method public void setTextSelectHandle(int);
+    method public void setTextSelectHandleLeft(android.graphics.drawable.Drawable);
+    method public void setTextSelectHandleLeft(int);
+    method public void setTextSelectHandleRight(android.graphics.drawable.Drawable);
+    method public void setTextSelectHandleRight(int);
     method public void setTextSize(float);
     method public void setTextSize(int, float);
     method public final void setTransformationMethod(android.text.method.TransformationMethod);
diff --git a/api/system-current.txt b/api/system-current.txt
index 10cf633..3074efd 100644
--- a/api/system-current.txt
+++ b/api/system-current.txt
@@ -24,6 +24,7 @@
     field public static final java.lang.String BIND_DIRECTORY_SEARCH = "android.permission.BIND_DIRECTORY_SEARCH";
     field public static final java.lang.String BIND_EUICC_SERVICE = "android.permission.BIND_EUICC_SERVICE";
     field public static final java.lang.String BIND_IMS_SERVICE = "android.permission.BIND_IMS_SERVICE";
+    field public static final java.lang.String BIND_INTELLIGENCE_SERVICE = "android.permission.BIND_INTELLIGENCE_SERVICE";
     field public static final java.lang.String BIND_KEYGUARD_APPWIDGET = "android.permission.BIND_KEYGUARD_APPWIDGET";
     field public static final java.lang.String BIND_NETWORK_RECOMMENDATION_SERVICE = "android.permission.BIND_NETWORK_RECOMMENDATION_SERVICE";
     field public static final java.lang.String BIND_NOTIFICATION_ASSISTANT_SERVICE = "android.permission.BIND_NOTIFICATION_ASSISTANT_SERVICE";
@@ -294,8 +295,11 @@
   }
 
   public class AppOpsManager {
+    method public java.util.List<android.app.AppOpsManager.HistoricalPackageOps> getAllHistoricPackagesOps(java.lang.String[], long, long);
+    method public android.app.AppOpsManager.HistoricalPackageOps getHistoricalPackagesOps(int, java.lang.String, java.lang.String[], long, long);
     method public static java.lang.String[] getOpStrs();
     method public java.util.List<android.app.AppOpsManager.PackageOps> getOpsForPackage(int, java.lang.String, int[]);
+    method public java.util.List<android.app.AppOpsManager.PackageOps> getPackagesForOpStrs(java.lang.String[]);
     method public static java.lang.String opToPermission(java.lang.String);
     method public void resetUidMode(java.lang.String, int, boolean);
     method public void setMode(java.lang.String, int, java.lang.String, int);
@@ -343,6 +347,39 @@
     field public static final java.lang.String OPSTR_WRITE_ICC_SMS = "android:write_icc_sms";
     field public static final java.lang.String OPSTR_WRITE_SMS = "android:write_sms";
     field public static final java.lang.String OPSTR_WRITE_WALLPAPER = "android:write_wallpaper";
+    field public static final int UID_STATE_BACKGROUND = 4; // 0x4
+    field public static final int UID_STATE_CACHED = 5; // 0x5
+    field public static final int UID_STATE_FOREGROUND = 3; // 0x3
+    field public static final int UID_STATE_FOREGROUND_SERVICE = 2; // 0x2
+    field public static final int UID_STATE_PERSISTENT = 0; // 0x0
+    field public static final int UID_STATE_TOP = 1; // 0x1
+  }
+
+  public static final class AppOpsManager.HistoricalOpEntry implements android.os.Parcelable {
+    method public int describeContents();
+    method public long getAccessCount(int);
+    method public long getAccessDuration(int);
+    method public long getBackgroundAccessCount();
+    method public long getBackgroundAccessDuration();
+    method public long getBackgroundRejectCount();
+    method public long getForegroundAccessCount();
+    method public long getForegroundAccessDuration();
+    method public long getForegroundRejectCount();
+    method public java.lang.String getOp();
+    method public long getRejectCount(int);
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalOpEntry> CREATOR;
+  }
+
+  public static final class AppOpsManager.HistoricalPackageOps implements android.os.Parcelable {
+    method public int describeContents();
+    method public android.app.AppOpsManager.HistoricalOpEntry getEntry(java.lang.String);
+    method public android.app.AppOpsManager.HistoricalOpEntry getEntryAt(int);
+    method public int getEntryCount();
+    method public java.lang.String getPackageName();
+    method public int getUid();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalPackageOps> CREATOR;
   }
 
   public static final class AppOpsManager.OpEntry implements android.os.Parcelable {
@@ -578,6 +615,14 @@
 
 }
 
+package android.app.assist {
+
+  public static class AssistStructure.ViewNode {
+    ctor public AssistStructure.ViewNode();
+  }
+
+}
+
 package android.app.backup {
 
   public class BackupDataInput {
@@ -4825,6 +4870,36 @@
 
 }
 
+package android.service.intelligence {
+
+  public abstract class IntelligenceService extends android.app.Service {
+    ctor public IntelligenceService();
+    method public abstract void onContentCaptureEvent(android.service.intelligence.InteractionSessionId, java.util.List<android.view.intelligence.ContentCaptureEvent>);
+    method public void onCreateInteractionSession(android.service.intelligence.InteractionContext, android.service.intelligence.InteractionSessionId);
+    method public void onDestroyInteractionSession(android.service.intelligence.InteractionSessionId);
+    field public static final java.lang.String SERVICE_INTERFACE = "android.service.intelligence.IntelligenceService";
+  }
+
+  public final class InteractionContext implements android.os.Parcelable {
+    method public int describeContents();
+    method public android.content.ComponentName getActivityComponent();
+    method public int getDisplayId();
+    method public int getFlags();
+    method public int getTaskId();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.service.intelligence.InteractionContext> CREATOR;
+    field public static final int FLAG_DISABLED_BY_APP = 1; // 0x1
+    field public static final int FLAG_DISABLED_BY_FLAG_SECURE = 2; // 0x2
+  }
+
+  public final class InteractionSessionId implements android.os.Parcelable {
+    method public int describeContents();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.service.intelligence.InteractionSessionId> CREATOR;
+  }
+
+}
+
 package android.service.notification {
 
   public final class Adjustment implements android.os.Parcelable {
@@ -6862,6 +6937,40 @@
 
 }
 
+package android.view.intelligence {
+
+  public final class ContentCaptureEvent implements android.os.Parcelable {
+    method public int describeContents();
+    method public long getEventTime();
+    method public int getFlags();
+    method public android.view.autofill.AutofillId getId();
+    method public java.lang.CharSequence getText();
+    method public int getType();
+    method public android.view.intelligence.ViewNode getViewNode();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.view.intelligence.ContentCaptureEvent> CREATOR;
+    field public static final int TYPE_ACTIVITY_PAUSED = 3; // 0x3
+    field public static final int TYPE_ACTIVITY_RESUMED = 2; // 0x2
+    field public static final int TYPE_ACTIVITY_STARTED = 1; // 0x1
+    field public static final int TYPE_ACTIVITY_STOPPED = 4; // 0x4
+    field public static final int TYPE_VIEW_ADDED = 5; // 0x5
+    field public static final int TYPE_VIEW_REMOVED = 6; // 0x6
+    field public static final int TYPE_VIEW_TEXT_CHANGED = 7; // 0x7
+  }
+
+  public final class IntelligenceManager {
+    method public java.util.Set<android.content.ComponentName> getContentCaptureDisabledActivities();
+    method public java.util.Set<java.lang.String> getContentCaptureDisabledPackages();
+    method public void setActivityContentCaptureEnabled(android.content.ComponentName, boolean);
+    method public void setPackageContentCaptureEnabled(java.lang.String, boolean);
+  }
+
+  public final class ViewNode extends android.app.assist.AssistStructure.ViewNode {
+    method public android.view.autofill.AutofillId getParentAutofillId();
+  }
+
+}
+
 package android.webkit {
 
   public abstract class CookieManager {
diff --git a/api/test-current.txt b/api/test-current.txt
index b59eacc..604eebd 100644
--- a/api/test-current.txt
+++ b/api/test-current.txt
@@ -78,6 +78,8 @@
   }
 
   public class AppOpsManager {
+    method public java.util.List<android.app.AppOpsManager.HistoricalPackageOps> getAllHistoricPackagesOps(java.lang.String[], long, long);
+    method public android.app.AppOpsManager.HistoricalPackageOps getHistoricalPackagesOps(int, java.lang.String, java.lang.String[], long, long);
     method public static int getNumOps();
     method public static java.lang.String[] getOpStrs();
     method public boolean isOperationActive(int, int, java.lang.String);
@@ -135,6 +137,33 @@
     field public static final int OP_SYSTEM_ALERT_WINDOW = 24; // 0x18
   }
 
+  public static final class AppOpsManager.HistoricalOpEntry implements android.os.Parcelable {
+    method public int describeContents();
+    method public long getAccessCount(int);
+    method public long getAccessDuration(int);
+    method public long getBackgroundAccessCount();
+    method public long getBackgroundAccessDuration();
+    method public long getBackgroundRejectCount();
+    method public long getForegroundAccessCount();
+    method public long getForegroundAccessDuration();
+    method public long getForegroundRejectCount();
+    method public java.lang.String getOp();
+    method public long getRejectCount(int);
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalOpEntry> CREATOR;
+  }
+
+  public static final class AppOpsManager.HistoricalPackageOps implements android.os.Parcelable {
+    method public int describeContents();
+    method public android.app.AppOpsManager.HistoricalOpEntry getEntry(java.lang.String);
+    method public android.app.AppOpsManager.HistoricalOpEntry getEntryAt(int);
+    method public int getEntryCount();
+    method public java.lang.String getPackageName();
+    method public int getUid();
+    method public void writeToParcel(android.os.Parcel, int);
+    field public static final android.os.Parcelable.Creator<android.app.AppOpsManager.HistoricalPackageOps> CREATOR;
+  }
+
   public static abstract interface AppOpsManager.OnOpActiveChangedListener {
     method public abstract void onOpActiveChanged(int, int, java.lang.String, boolean);
   }
@@ -1323,6 +1352,14 @@
 
 }
 
+package android.util {
+
+  public final class ArraySet<E> implements java.util.Collection java.util.Set {
+    method public E valueAtUnchecked(int);
+  }
+
+}
+
 package android.util.proto {
 
   public final class EncodedBuffer {
diff --git a/cmds/statsd/Android.bp b/cmds/statsd/Android.bp
index a3cd8a3..6547b3a 100644
--- a/cmds/statsd/Android.bp
+++ b/cmds/statsd/Android.bp
@@ -205,6 +205,10 @@
     ],
 
     srcs: [
+        // atom_field_options.proto needs field_options.proto, but that is
+        // not included in libprotobuf-cpp-lite, so compile it here.
+        ":libprotobuf-internal-protos",
+
         "src/atom_field_options.proto",
         "src/atoms.proto",
         "src/stats_log.proto",
@@ -259,11 +263,11 @@
     ],
 
     proto: {
-        type: "full",
+        type: "lite",
         include_dirs: ["external/protobuf/src"],
     },
 
-    shared_libs: ["libprotobuf-cpp-full"],
+    shared_libs: ["libprotobuf-cpp-lite"],
 
 }
 
@@ -276,6 +280,10 @@
     defaults: ["statsd_defaults"],
 
     srcs: [
+        // atom_field_options.proto needs field_options.proto, but that is
+        // not included in libprotobuf-cpp-lite, so compile it here.
+        ":libprotobuf-internal-protos",
+
         "src/atom_field_options.proto",
         "src/atoms.proto",
         "src/stats_log.proto",
@@ -290,7 +298,7 @@
     ],
 
     proto: {
-        type: "full",
+        type: "lite",
         include_dirs: ["external/protobuf/src"],
     },
 
@@ -312,7 +320,7 @@
     shared_libs: [
         "libgtest_prod",
         "libstatslog",
-        "libprotobuf-cpp-full",
+        "libprotobuf-cpp-lite",
     ],
 }
 
diff --git a/cmds/statsd/src/anomaly/AnomalyTracker.cpp b/cmds/statsd/src/anomaly/AnomalyTracker.cpp
index ee111cd..13ab844 100644
--- a/cmds/statsd/src/anomaly/AnomalyTracker.cpp
+++ b/cmds/statsd/src/anomaly/AnomalyTracker.cpp
@@ -24,6 +24,7 @@
 #include "subscriber/IncidentdReporter.h"
 #include "subscriber/SubscriberReporter.h"
 
+#include <inttypes.h>
 #include <statslog.h>
 #include <time.h>
 
@@ -223,7 +224,7 @@
     }
 
     if (!mSubscriptions.empty()) {
-        ALOGI("An anomaly (%lld) %s has occurred! Informing subscribers.",
+        ALOGI("An anomaly (%" PRId64 ") %s has occurred! Informing subscribers.",
                 mAlert.id(), key.toString().c_str());
         informSubscribers(key);
     } else {
diff --git a/cmds/statsd/src/metrics/metrics_manager_util.cpp b/cmds/statsd/src/metrics/metrics_manager_util.cpp
index 136ba07..4a9b521 100644
--- a/cmds/statsd/src/metrics/metrics_manager_util.cpp
+++ b/cmds/statsd/src/metrics/metrics_manager_util.cpp
@@ -35,6 +35,8 @@
 #include "stats_util.h"
 #include "statslog.h"
 
+#include <inttypes.h>
+
 using std::set;
 using std::string;
 using std::unordered_map;
@@ -573,7 +575,7 @@
     for (int i = 0; i < config.no_report_metric_size(); ++i) {
         const auto no_report_metric = config.no_report_metric(i);
         if (metricMap.find(no_report_metric) == metricMap.end()) {
-            ALOGW("no_report_metric %lld not exist", no_report_metric);
+            ALOGW("no_report_metric %" PRId64 " not exist", no_report_metric);
             return false;
         }
         noReportMetricIds.insert(no_report_metric);
diff --git a/config/hiddenapi-light-greylist.txt b/config/hiddenapi-light-greylist.txt
index 7382cd3..43e926f 100644
--- a/config/hiddenapi-light-greylist.txt
+++ b/config/hiddenapi-light-greylist.txt
@@ -2299,84 +2299,3 @@
 Lorg/ccil/cowan/tagsoup/Schema;->thePrefix:Ljava/lang/String;
 Lorg/ccil/cowan/tagsoup/Schema;->theRoot:Lorg/ccil/cowan/tagsoup/ElementType;
 Lorg/ccil/cowan/tagsoup/Schema;->theURI:Ljava/lang/String;
-Lsun/misc/Cleaner;->clean()V
-Lsun/misc/Unsafe;->addressSize()I
-Lsun/misc/Unsafe;->allocateInstance(Ljava/lang/Class;)Ljava/lang/Object;
-Lsun/misc/Unsafe;->allocateMemory(J)J
-Lsun/misc/Unsafe;->arrayBaseOffset(Ljava/lang/Class;)I
-Lsun/misc/Unsafe;->arrayIndexScale(Ljava/lang/Class;)I
-Lsun/misc/Unsafe;->compareAndSwapInt(Ljava/lang/Object;JII)Z
-Lsun/misc/Unsafe;->compareAndSwapLong(Ljava/lang/Object;JJJ)Z
-Lsun/misc/Unsafe;->compareAndSwapObject(Ljava/lang/Object;JLjava/lang/Object;Ljava/lang/Object;)Z
-Lsun/misc/Unsafe;->copyMemory(JJJ)V
-Lsun/misc/Unsafe;->copyMemoryFromPrimitiveArray(Ljava/lang/Object;JJJ)V
-Lsun/misc/Unsafe;->copyMemoryToPrimitiveArray(JLjava/lang/Object;JJ)V
-Lsun/misc/Unsafe;->freeMemory(J)V
-Lsun/misc/Unsafe;->fullFence()V
-Lsun/misc/Unsafe;->getAndAddInt(Ljava/lang/Object;JI)I
-Lsun/misc/Unsafe;->getAndAddLong(Ljava/lang/Object;JJ)J
-Lsun/misc/Unsafe;->getAndSetInt(Ljava/lang/Object;JI)I
-Lsun/misc/Unsafe;->getAndSetLong(Ljava/lang/Object;JJ)J
-Lsun/misc/Unsafe;->getAndSetObject(Ljava/lang/Object;JLjava/lang/Object;)Ljava/lang/Object;
-Lsun/misc/Unsafe;->getArrayBaseOffsetForComponentType(Ljava/lang/Class;)I
-Lsun/misc/Unsafe;->getArrayIndexScaleForComponentType(Ljava/lang/Class;)I
-Lsun/misc/Unsafe;->getBoolean(Ljava/lang/Object;J)Z
-Lsun/misc/Unsafe;->getByte(J)B
-Lsun/misc/Unsafe;->getByte(Ljava/lang/Object;J)B
-Lsun/misc/Unsafe;->getChar(J)C
-Lsun/misc/Unsafe;->getChar(Ljava/lang/Object;J)C
-Lsun/misc/Unsafe;->getDouble(J)D
-Lsun/misc/Unsafe;->getDouble(Ljava/lang/Object;J)D
-Lsun/misc/Unsafe;->getFloat(J)F
-Lsun/misc/Unsafe;->getFloat(Ljava/lang/Object;J)F
-Lsun/misc/Unsafe;->getInt(J)I
-Lsun/misc/Unsafe;->getInt(Ljava/lang/Object;J)I
-Lsun/misc/Unsafe;->getIntVolatile(Ljava/lang/Object;J)I
-Lsun/misc/Unsafe;->getLong(J)J
-Lsun/misc/Unsafe;->getLong(Ljava/lang/Object;J)J
-Lsun/misc/Unsafe;->getLongVolatile(Ljava/lang/Object;J)J
-Lsun/misc/Unsafe;->getObject(Ljava/lang/Object;J)Ljava/lang/Object;
-Lsun/misc/Unsafe;->getObjectVolatile(Ljava/lang/Object;J)Ljava/lang/Object;
-Lsun/misc/Unsafe;->getShort(J)S
-Lsun/misc/Unsafe;->getShort(Ljava/lang/Object;J)S
-Lsun/misc/Unsafe;->getUnsafe()Lsun/misc/Unsafe;
-Lsun/misc/Unsafe;->INVALID_FIELD_OFFSET:I
-Lsun/misc/Unsafe;->loadFence()V
-Lsun/misc/Unsafe;->objectFieldOffset(Ljava/lang/reflect/Field;)J
-Lsun/misc/Unsafe;->pageSize()I
-Lsun/misc/Unsafe;->park(ZJ)V
-Lsun/misc/Unsafe;->putBoolean(Ljava/lang/Object;JZ)V
-Lsun/misc/Unsafe;->putByte(JB)V
-Lsun/misc/Unsafe;->putByte(Ljava/lang/Object;JB)V
-Lsun/misc/Unsafe;->putChar(JC)V
-Lsun/misc/Unsafe;->putChar(Ljava/lang/Object;JC)V
-Lsun/misc/Unsafe;->putDouble(JD)V
-Lsun/misc/Unsafe;->putDouble(Ljava/lang/Object;JD)V
-Lsun/misc/Unsafe;->putFloat(JF)V
-Lsun/misc/Unsafe;->putFloat(Ljava/lang/Object;JF)V
-Lsun/misc/Unsafe;->putInt(JI)V
-Lsun/misc/Unsafe;->putInt(Ljava/lang/Object;JI)V
-Lsun/misc/Unsafe;->putIntVolatile(Ljava/lang/Object;JI)V
-Lsun/misc/Unsafe;->putLong(JJ)V
-Lsun/misc/Unsafe;->putLong(Ljava/lang/Object;JJ)V
-Lsun/misc/Unsafe;->putLongVolatile(Ljava/lang/Object;JJ)V
-Lsun/misc/Unsafe;->putObject(Ljava/lang/Object;JLjava/lang/Object;)V
-Lsun/misc/Unsafe;->putObjectVolatile(Ljava/lang/Object;JLjava/lang/Object;)V
-Lsun/misc/Unsafe;->putOrderedInt(Ljava/lang/Object;JI)V
-Lsun/misc/Unsafe;->putOrderedLong(Ljava/lang/Object;JJ)V
-Lsun/misc/Unsafe;->putOrderedObject(Ljava/lang/Object;JLjava/lang/Object;)V
-Lsun/misc/Unsafe;->putShort(JS)V
-Lsun/misc/Unsafe;->putShort(Ljava/lang/Object;JS)V
-Lsun/misc/Unsafe;->setMemory(JJB)V
-Lsun/misc/Unsafe;->storeFence()V
-Lsun/misc/Unsafe;->theUnsafe:Lsun/misc/Unsafe;
-Lsun/misc/Unsafe;->THE_ONE:Lsun/misc/Unsafe;
-Lsun/misc/Unsafe;->unpark(Ljava/lang/Object;)V
-Lsun/misc/URLClassPath$JarLoader;->getJarFile()Ljava/util/jar/JarFile;
-Lsun/misc/URLClassPath;->lmap:Ljava/util/HashMap;
-Lsun/misc/URLClassPath;->loaders:Ljava/util/ArrayList;
-Lsun/misc/URLClassPath;->urls:Ljava/util/Stack;
-Lsun/nio/ch/DirectBuffer;->cleaner()Lsun/misc/Cleaner;
-Lsun/security/x509/AlgorithmId;->get(Ljava/lang/String;)Lsun/security/x509/AlgorithmId;
-Lsun/security/x509/AlgorithmId;->getName()Ljava/lang/String;
-Lsun/security/x509/AVA;->hasRFC2253Keyword()Z
diff --git a/core/java/android/app/AppOpsManager.aidl b/core/java/android/app/AppOpsManager.aidl
index 4b97a15..9329fbc 100644
--- a/core/java/android/app/AppOpsManager.aidl
+++ b/core/java/android/app/AppOpsManager.aidl
@@ -18,3 +18,6 @@
 
 parcelable AppOpsManager.PackageOps;
 parcelable AppOpsManager.OpEntry;
+
+parcelable AppOpsManager.HistoricalPackageOps;
+parcelable AppOpsManager.HistoricalOpEntry;
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 690bf3c..7df8de0 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -17,6 +17,7 @@
 package android.app;
 
 import android.Manifest;
+import android.annotation.IntDef;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.RequiresPermission;
@@ -26,6 +27,7 @@
 import android.annotation.UnsupportedAppUsage;
 import android.app.usage.UsageStatsManager;
 import android.content.Context;
+import android.content.pm.ParceledListSlice;
 import android.media.AudioAttributes.AttributeUsage;
 import android.os.Binder;
 import android.os.IBinder;
@@ -34,7 +36,6 @@
 import android.os.Process;
 import android.os.RemoteException;
 import android.os.UserManager;
-import android.provider.Settings;
 import android.util.ArrayMap;
 
 import com.android.internal.app.IAppOpsActiveCallback;
@@ -42,8 +43,11 @@
 import com.android.internal.app.IAppOpsService;
 import com.android.internal.util.Preconditions;
 
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 
@@ -139,22 +143,38 @@
             "foreground",   // MODE_FOREGROUND
     };
 
+
+    /** @hide */
+    @Retention(RetentionPolicy.SOURCE)
+    @IntDef(flag = true, prefix = { "UID_STATE_" }, value = {
+            UID_STATE_PERSISTENT,
+            UID_STATE_TOP,
+            UID_STATE_FOREGROUND_SERVICE,
+            UID_STATE_FOREGROUND,
+            UID_STATE_BACKGROUND,
+            UID_STATE_CACHED
+    })
+    public @interface UidState {}
+
     /**
      * Metrics about an op when its uid is persistent.
      * @hide
      */
+    @SystemApi
     public static final int UID_STATE_PERSISTENT = 0;
 
     /**
      * Metrics about an op when its uid is at the top.
      * @hide
      */
+    @SystemApi
     public static final int UID_STATE_TOP = 1;
 
     /**
      * Metrics about an op when its uid is running a foreground service.
      * @hide
      */
+    @SystemApi
     public static final int UID_STATE_FOREGROUND_SERVICE = 2;
 
     /**
@@ -167,18 +187,21 @@
      * Metrics about an op when its uid is in the foreground for any other reasons.
      * @hide
      */
+    @SystemApi
     public static final int UID_STATE_FOREGROUND = 3;
 
     /**
      * Metrics about an op when its uid is in the background for any reason.
      * @hide
      */
+    @SystemApi
     public static final int UID_STATE_BACKGROUND = 4;
 
     /**
      * Metrics about an op when its uid is cached.
      * @hide
      */
+    @SystemApi
     public static final int UID_STATE_CACHED = 5;
 
     /**
@@ -1585,26 +1608,6 @@
      * @hide
      */
     public static int opToDefaultMode(int op) {
-        // STOPSHIP b/118520006: Hardcode the default values once the feature is stable.
-        switch (op) {
-            // SMS permissions
-            case AppOpsManager.OP_SEND_SMS:
-            case AppOpsManager.OP_RECEIVE_SMS:
-            case AppOpsManager.OP_READ_SMS:
-            case AppOpsManager.OP_RECEIVE_WAP_PUSH:
-            case AppOpsManager.OP_RECEIVE_MMS:
-            case AppOpsManager.OP_READ_CELL_BROADCASTS:
-            // CallLog permissions
-            case AppOpsManager.OP_READ_CALL_LOG:
-            case AppOpsManager.OP_WRITE_CALL_LOG:
-            case AppOpsManager.OP_PROCESS_OUTGOING_CALLS: {
-                // ActivityThread.currentApplication() is never null
-                if (Settings.Global.getInt(ActivityThread.currentApplication().getContentResolver(),
-                        Settings.Global.SMS_ACCESS_RESTRICTION_ENABLED, 0) == 1) {
-                    return AppOpsManager.MODE_DEFAULT;
-                }
-            }
-        }
         return sOpDefaultMode[op];
     }
 
@@ -1904,6 +1907,377 @@
     }
 
     /**
+     * This class represents historical app op information about a package. The history
+     * is aggregated information about ops for a certain amount of time such
+     * as the times the op was accessed, the times the op was rejected, the total
+     * duration the app op has been accessed.
+     *
+     * @hide
+     */
+    @TestApi
+    @SystemApi
+    public static final class HistoricalPackageOps implements Parcelable {
+        private final int mUid;
+        private final @NonNull String mPackageName;
+        private final @NonNull List<HistoricalOpEntry> mEntries;
+
+        /**
+         * @hide
+         */
+        public HistoricalPackageOps(int uid, @NonNull String packageName) {
+            mUid = uid;
+            mPackageName = packageName;
+            mEntries = new ArrayList<>();
+        }
+
+        HistoricalPackageOps(@NonNull Parcel parcel) {
+            mUid = parcel.readInt();
+            mPackageName = parcel.readString();
+            mEntries = parcel.createTypedArrayList(HistoricalOpEntry.CREATOR);
+        }
+
+        /**
+         * @hide
+         */
+        public void addEntry(@NonNull HistoricalOpEntry entry) {
+            mEntries.add(entry);
+        }
+
+        /**
+         * Gets the package name which the data represents.
+         *
+         * @return The package name which the data represents.
+         */
+        public @NonNull String getPackageName() {
+            return mPackageName;
+        }
+
+        /**
+         *  Gets the UID which the data represents.
+         *
+         * @return The UID which the data represents.
+         */
+        public int getUid() {
+            return mUid;
+        }
+
+        /**
+         * Gets number historical app op entries.
+         *
+         * @return The number historical app op entries.
+         *
+         * @see #getEntryAt(int)
+         */
+        public int getEntryCount() {
+            return mEntries.size();
+        }
+
+        /**
+         * Gets the historical at a given index.
+         *
+         * @param index The index to lookup.
+         *
+         * @return The entry at the given index.
+         *
+         * @see #getEntryCount()
+         */
+        public @NonNull HistoricalOpEntry getEntryAt(int index) {
+            return mEntries.get(index);
+        }
+
+        /**
+         * Gets the historical entry for a given op name.
+         *
+         * @param opName The op name.
+         *
+         * @return The historical entry for that op name.
+         */
+        public @Nullable HistoricalOpEntry getEntry(@NonNull String opName) {
+            final int entryCount = mEntries.size();
+            for (int i = 0; i < entryCount; i++) {
+                final HistoricalOpEntry entry = mEntries.get(i);
+                if (entry.getOp().equals(opName)) {
+                    return entry;
+                }
+            }
+            return null;
+        }
+
+        @Override
+        public int describeContents() {
+            return 0;
+        }
+
+        @Override
+        public void writeToParcel(@NonNull Parcel parcel, int flags) {
+            parcel.writeInt(mUid);
+            parcel.writeString(mPackageName);
+            parcel.writeTypedList(mEntries, flags);
+        }
+
+        public static final Creator<HistoricalPackageOps> CREATOR =
+                new Creator<HistoricalPackageOps>() {
+            @Override
+            public @NonNull HistoricalPackageOps createFromParcel(@NonNull Parcel parcel) {
+                return new HistoricalPackageOps(parcel);
+            }
+
+            @Override
+            public @NonNull HistoricalPackageOps[] newArray(int size) {
+                return new HistoricalPackageOps[size];
+            }
+        };
+    }
+
+    /**
+     * This class represents historical information about an app op. The history
+     * is aggregated information about the op for a certain amount of time such
+     * as the times the op was accessed, the times the op was rejected, the total
+     * duration the app op has been accessed.
+     *
+     * @hide
+     */
+    @TestApi
+    @SystemApi
+    public static final class HistoricalOpEntry implements Parcelable {
+        private final int mOp;
+        private final long[] mAccessCount;
+        private final long[] mRejectCount;
+        private final long[] mAccessDuration;
+
+        /**
+         * @hide
+         */
+        public HistoricalOpEntry(int op) {
+            mOp = op;
+            mAccessCount = new long[_NUM_UID_STATE];
+            mRejectCount = new long[_NUM_UID_STATE];
+            mAccessDuration = new long[_NUM_UID_STATE];
+        }
+
+        HistoricalOpEntry(@NonNull Parcel parcel) {
+            mOp = parcel.readInt();
+            mAccessCount = parcel.createLongArray();
+            mRejectCount = parcel.createLongArray();
+            mAccessDuration = parcel.createLongArray();
+        }
+
+        /**
+         * @hide
+         */
+        public void addEntry(@UidState int uidState, long accessCount,
+                long rejectCount, long accessDuration) {
+            mAccessCount[uidState] = accessCount;
+            mRejectCount[uidState] = rejectCount;
+            mAccessDuration[uidState] = accessDuration;
+        }
+
+        /**
+         * Gets the op name.
+         *
+         * @return The op name.
+         */
+        public @NonNull String getOp() {
+            return sOpToString[mOp];
+        }
+
+        /**
+         * Gets the number times the op was accessed (performed) in the foreground.
+         *
+         * @return The times the op was accessed in the foreground.
+         *
+         * @see #getBackgroundAccessCount()
+         * @see #getAccessCount(int)
+         */
+        public long getForegroundAccessCount() {
+            return sum(mAccessCount, UID_STATE_PERSISTENT, UID_STATE_LAST_NON_RESTRICTED + 1);
+        }
+
+        /**
+         * Gets the number times the op was accessed (performed) in the background.
+         *
+         * @return The times the op was accessed in the background.
+         *
+         * @see #getForegroundAccessCount()
+         * @see #getAccessCount(int)
+         */
+        public long getBackgroundAccessCount() {
+            return sum(mAccessCount, UID_STATE_LAST_NON_RESTRICTED + 1, _NUM_UID_STATE);
+        }
+
+        /**
+         * Gets the number times the op was accessed (performed) for a given uid state.
+         *
+         * @param uidState The UID state for which to query. Could be one of
+         * {@link #UID_STATE_PERSISTENT}, {@link #UID_STATE_TOP},
+         * {@link #UID_STATE_FOREGROUND_SERVICE}, {@link #UID_STATE_FOREGROUND},
+         * {@link #UID_STATE_BACKGROUND}, {@link #UID_STATE_CACHED}.
+         *
+         * @return The times the op was accessed for the given UID state.
+         *
+         * @see #getForegroundAccessCount()
+         * @see #getBackgroundAccessCount()
+         */
+        public long getAccessCount(@UidState int uidState) {
+            return mAccessCount[uidState];
+        }
+
+        /**
+         * Gets the number times the op was rejected in the foreground.
+         *
+         * @return The times the op was rejected in the foreground.
+         *
+         * @see #getBackgroundRejectCount()
+         * @see #getRejectCount(int)
+         */
+        public long getForegroundRejectCount() {
+            return sum(mRejectCount, UID_STATE_PERSISTENT, UID_STATE_LAST_NON_RESTRICTED + 1);
+        }
+
+        /**
+         * Gets the number times the op was rejected in the background.
+         *
+         * @return The times the op was rejected in the background.
+         *
+         * @see #getForegroundRejectCount()
+         * @see #getRejectCount(int)
+         */
+        public long getBackgroundRejectCount() {
+            return sum(mRejectCount, UID_STATE_LAST_NON_RESTRICTED + 1, _NUM_UID_STATE);
+        }
+
+        /**
+         * Gets the number times the op was rejected for a given uid state.
+         *
+         * @param uidState The UID state for which to query. Could be one of
+         * {@link #UID_STATE_PERSISTENT}, {@link #UID_STATE_TOP},
+         * {@link #UID_STATE_FOREGROUND_SERVICE}, {@link #UID_STATE_FOREGROUND},
+         * {@link #UID_STATE_BACKGROUND}, {@link #UID_STATE_CACHED}.
+         *
+         * @return The times the op was rejected for the given UID state.
+         *
+         * @see #getForegroundRejectCount()
+         * @see #getBackgroundRejectCount()
+         */
+        public long getRejectCount(@UidState int uidState) {
+            return mRejectCount[uidState];
+        }
+
+        /**
+         * Gets the total duration the app op was accessed (performed) in the foreground.
+         *
+         * @return The total duration the app op was accessed in the foreground.
+         *
+         * @see #getBackgroundAccessDuration()
+         * @see #getAccessDuration(int)
+         */
+        public long getForegroundAccessDuration() {
+            return sum(mAccessDuration, UID_STATE_PERSISTENT, UID_STATE_LAST_NON_RESTRICTED + 1);
+        }
+
+        /**
+         * Gets the total duration the app op was accessed (performed) in the background.
+         *
+         * @return The total duration the app op was accessed in the background.
+         *
+         * @see #getForegroundAccessDuration()
+         * @see #getAccessDuration(int)
+         */
+        public long getBackgroundAccessDuration() {
+            return sum(mAccessDuration, UID_STATE_LAST_NON_RESTRICTED + 1, _NUM_UID_STATE);
+        }
+
+        /**
+         * Gets the total duration the app op was accessed (performed) for a given UID state.
+         *
+         * @param uidState The UID state for which to query. Could be one of
+         * {@link #UID_STATE_PERSISTENT}, {@link #UID_STATE_TOP},
+         * {@link #UID_STATE_FOREGROUND_SERVICE}, {@link #UID_STATE_FOREGROUND},
+         * {@link #UID_STATE_BACKGROUND}, {@link #UID_STATE_CACHED}.
+         *
+         * @return The total duration the app op was accessed for the given UID state.
+         *
+         * @see #getForegroundAccessDuration()
+         * @see #getBackgroundAccessDuration()
+         */
+        public long getAccessDuration(@UidState int uidState) {
+            return mAccessDuration[uidState];
+        }
+
+        @Override
+        public int describeContents() {
+            return 0;
+        }
+
+        @Override
+        public void writeToParcel(Parcel parcel, int flags) {
+            parcel.writeInt(mOp);
+            parcel.writeLongArray(mAccessCount);
+            parcel.writeLongArray(mRejectCount);
+            parcel.writeLongArray(mAccessDuration);
+        }
+
+        @Override
+        public boolean equals(Object other) {
+            if (this == other) {
+                return true;
+            }
+            if (other == null || getClass() != other.getClass()) {
+                return false;
+            }
+            final HistoricalOpEntry otherInstance = (HistoricalOpEntry) other;
+            if (mOp != otherInstance.mOp) {
+                return false;
+            }
+            if (!Arrays.equals(mAccessCount, otherInstance.mAccessCount)) {
+                return false;
+            }
+            if (!Arrays.equals(mRejectCount, otherInstance.mRejectCount)) {
+                return false;
+            }
+            return Arrays.equals(mAccessDuration, otherInstance.mAccessDuration);
+        }
+
+        @Override
+        public int hashCode() {
+            int result = mOp;
+            result = 31 * result + Arrays.hashCode(mAccessCount);
+            result = 31 * result + Arrays.hashCode(mRejectCount);
+            result = 31 * result + Arrays.hashCode(mAccessDuration);
+            return result;
+        }
+
+        /**
+         *
+         * Computes the sum given the start and end index.
+         *
+         * @param counts The data array.
+         * @param start The start index (inclusive)
+         * @param end The end index (exclusive)
+         * @return The sum.
+         */
+        private static long sum(@NonNull long[] counts, int start, int end) {
+            long totalCount = 0;
+            for (int i = start; i <= end; i++) {
+                totalCount += counts[i];
+            }
+            return totalCount;
+        }
+
+        public static final Creator<HistoricalOpEntry> CREATOR = new Creator<HistoricalOpEntry>() {
+            @Override
+            public @NonNull HistoricalOpEntry createFromParcel(@NonNull Parcel source) {
+                return new HistoricalOpEntry(source);
+            }
+
+            @Override
+            public @NonNull HistoricalOpEntry[] newArray(int size) {
+                return new HistoricalOpEntry[size];
+            }
+        };
+    }
+
+    /**
      * Callback for notification of changes to operation state.
      */
     public interface OnOpChangedListener {
@@ -1960,6 +2334,30 @@
     }
 
     /**
+     * Retrieve current operation state for all applications.
+     *
+     * @param ops The set of operations you are interested in, or null if you want all of them.
+     * @hide
+     */
+    @RequiresPermission(android.Manifest.permission.GET_APP_OPS_STATS)
+    @SystemApi
+    public List<AppOpsManager.PackageOps> getPackagesForOpStrs(String[] ops) {
+        if (ops == null) {
+            return getPackagesForOps(null);
+        }
+        final int[] opCodes = new int[ops.length];
+        for (int i = 0; i < ops.length; ++i) {
+            final Integer opCode = sOpStrToOp.get(ops[i]);
+            if (opCode == null) {
+                opCodes[i] = OP_NONE;
+            } else {
+                opCodes[i] = opCode;
+            }
+        }
+        return getPackagesForOps(opCodes);
+    }
+
+    /**
      * Retrieve current operation state for one application.
      *
      * @param uid The uid of the application of interest.
@@ -1978,6 +2376,74 @@
     }
 
     /**
+     * Retrieve historical app op stats for a package.
+     *
+     * @param uid The UID to query for.
+     * @param packageName The package to query for.
+     * @param beginTimeMillis The beginning of the interval in milliseconds since
+     *     epoch start (January 1, 1970 00:00:00.000 GMT - Gregorian). Must be non
+     *     negative.
+     * @param endTimeMillis The end of the interval in milliseconds since
+     *     epoch start (January 1, 1970 00:00:00.000 GMT - Gregorian). Must be after
+     *     {@code beginTimeMillis}.
+     * @param opNames The ops to query for. Pass {@code null} for all ops.
+     *
+     * @return The historical ops or {@code null} if there are no ops for this package.
+     *
+     * @throws IllegalArgumentException If any of the argument contracts is violated.
+     *
+     * @hide
+     */
+    @TestApi
+    @SystemApi
+    @RequiresPermission(android.Manifest.permission.GET_APP_OPS_STATS)
+    public @Nullable HistoricalPackageOps getHistoricalPackagesOps(
+            int uid, @NonNull String packageName, @Nullable String[] opNames,
+            long beginTimeMillis, long endTimeMillis) {
+        try {
+            return mService.getHistoricalPackagesOps(uid, packageName, opNames,
+                    beginTimeMillis, endTimeMillis);
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
+     * Retrieve historical app op stats for all packages.
+     *
+     * @param beginTimeMillis The beginning of the interval in milliseconds since
+     *     epoch start (January 1, 1970 00:00:00.000 GMT - Gregorian). Must be non
+     *     negative.
+     * @param endTimeMillis The end of the interval in milliseconds since
+     *     epoch start (January 1, 1970 00:00:00.000 GMT - Gregorian). Must be after
+     *     {@code beginTimeMillis}.
+     * @param opNames The ops to query for. Pass {@code null} for all ops.
+     *
+     * @return The historical ops or an empty list if there are no ops for any package.
+     *
+     * @throws IllegalArgumentException If any of the argument contracts is violated.
+     *
+     * @hide
+     */
+    @TestApi
+    @SystemApi
+    @RequiresPermission(android.Manifest.permission.GET_APP_OPS_STATS)
+    public @NonNull List<HistoricalPackageOps> getAllHistoricPackagesOps(
+            @Nullable String[] opNames, long beginTimeMillis, long endTimeMillis) {
+        try {
+            @SuppressWarnings("unchecked")
+            final ParceledListSlice<HistoricalPackageOps> payload =
+                    mService.getAllHistoricalPackagesOps(opNames, beginTimeMillis, endTimeMillis);
+            if (payload != null) {
+                return payload.getList();
+            }
+            return Collections.emptyList();
+        } catch (RemoteException e) {
+            throw e.rethrowFromSystemServer();
+        }
+    }
+
+    /**
      * Sets given app op in the specified mode for app ops in the UID.
      * This applies to all apps currently in the UID or installed in
      * this UID in the future.
diff --git a/core/java/android/app/AutomaticZenRule.java b/core/java/android/app/AutomaticZenRule.java
index 9d68133..e2f2075 100644
--- a/core/java/android/app/AutomaticZenRule.java
+++ b/core/java/android/app/AutomaticZenRule.java
@@ -31,7 +31,10 @@
  * Rule instance information for zen mode.
  */
 public final class AutomaticZenRule implements Parcelable {
-
+    /* @hide */
+    private static final int ENABLED = 1;
+    /* @hide */
+    private static final int DISABLED = 0;
     private boolean enabled = false;
     private String name;
     private @InterruptionFilter int interruptionFilter;
@@ -39,6 +42,7 @@
     private ComponentName owner;
     private long creationTime;
     private ZenPolicy mZenPolicy;
+    private boolean mModified = false;
 
     /**
      * Creates an automatic zen rule.
@@ -101,8 +105,8 @@
     }
 
     public AutomaticZenRule(Parcel source) {
-        enabled = source.readInt() == 1;
-        if (source.readInt() == 1) {
+        enabled = source.readInt() == ENABLED;
+        if (source.readInt() == ENABLED) {
             name = source.readString();
         }
         interruptionFilter = source.readInt();
@@ -110,6 +114,7 @@
         owner = source.readParcelable(null);
         creationTime = source.readLong();
         mZenPolicy = source.readParcelable(null);
+        mModified = source.readInt() == ENABLED;
     }
 
     /**
@@ -148,6 +153,14 @@
     }
 
     /**
+     * Returns whether this rule's name has been modified by the user.
+     * @hide
+     */
+    public boolean isModified() {
+        return mModified;
+    }
+
+    /**
      * Gets the zen policy.
      */
     public ZenPolicy getZenPolicy() {
@@ -191,6 +204,14 @@
     }
 
     /**
+     * Sets modified state of this rule.
+     * @hide
+     */
+    public void setModified(boolean modified) {
+        this.mModified = modified;
+    }
+
+    /**
      * Sets the zen policy.
      */
     public void setZenPolicy(ZenPolicy zenPolicy) {
@@ -204,7 +225,7 @@
 
     @Override
     public void writeToParcel(Parcel dest, int flags) {
-        dest.writeInt(enabled ? 1 : 0);
+        dest.writeInt(enabled ? ENABLED : DISABLED);
         if (name != null) {
             dest.writeInt(1);
             dest.writeString(name);
@@ -216,6 +237,7 @@
         dest.writeParcelable(owner, 0);
         dest.writeLong(creationTime);
         dest.writeParcelable(mZenPolicy, 0);
+        dest.writeInt(mModified ? ENABLED : DISABLED);
     }
 
     @Override
@@ -237,6 +259,7 @@
         if (o == this) return true;
         final AutomaticZenRule other = (AutomaticZenRule) o;
         return other.enabled == enabled
+                && other.mModified == mModified
                 && Objects.equals(other.name, name)
                 && other.interruptionFilter == interruptionFilter
                 && Objects.equals(other.conditionId, conditionId)
@@ -248,7 +271,7 @@
     @Override
     public int hashCode() {
         return Objects.hash(enabled, name, interruptionFilter, conditionId, owner, creationTime,
-                mZenPolicy);
+                mZenPolicy, mModified);
     }
 
     public static final Parcelable.Creator<AutomaticZenRule> CREATOR
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index 92daf08..f129a71 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -3845,6 +3845,11 @@
     public static final int KEYGUARD_DISABLE_IRIS = 1 << 8;
 
     /**
+     * NOTE: Please remember to update the DevicePolicyManagerTest's testKeyguardDisabledFeatures
+     * CTS test when adding to the list above.
+     */
+
+    /**
      * Disable all biometric authentication on keyguard secure screens (e.g. PIN/Pattern/Password).
      */
     public static final int KEYGUARD_DISABLE_BIOMETRICS =
diff --git a/core/java/android/app/assist/AssistStructure.java b/core/java/android/app/assist/AssistStructure.java
index fefb8d3..43f902a 100644
--- a/core/java/android/app/assist/AssistStructure.java
+++ b/core/java/android/app/assist/AssistStructure.java
@@ -2,6 +2,7 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
+import android.annotation.SystemApi;
 import android.app.Activity;
 import android.content.ComponentName;
 import android.content.Context;
@@ -713,7 +714,11 @@
 
         ViewNode[] mChildren;
 
-        ViewNode() {
+        // TODO(b/111276913): temporarily made public / @hide until we decide what will be used by
+        // ScreenObservation.
+        /** @hide */
+        @SystemApi
+        public ViewNode() {
         }
 
         ViewNode(ParcelTransferReader reader, int nestingLevel) {
diff --git a/core/java/android/content/res/FontResourcesParser.java b/core/java/android/content/res/FontResourcesParser.java
index 6a4aae6..14eb11a 100644
--- a/core/java/android/content/res/FontResourcesParser.java
+++ b/core/java/android/content/res/FontResourcesParser.java
@@ -76,6 +76,10 @@
 
     // A class represents font element in xml file which points a file in resource.
     public static final class FontFileResourceEntry {
+        public static final int RESOLVE_BY_FONT_TABLE = Typeface.RESOLVE_BY_FONT_TABLE;
+        public static final int UPRIGHT = 0;
+        public static final int ITALIC = 1;
+
         private final @NonNull String mFileName;
         private int mWeight;
         private int mItalic;
@@ -216,7 +220,7 @@
         int weight = array.getInt(R.styleable.FontFamilyFont_fontWeight,
                 Typeface.RESOLVE_BY_FONT_TABLE);
         int italic = array.getInt(R.styleable.FontFamilyFont_fontStyle,
-                Typeface.RESOLVE_BY_FONT_TABLE);
+                FontFileResourceEntry.RESOLVE_BY_FONT_TABLE);
         String variationSettings = array.getString(
                 R.styleable.FontFamilyFont_fontVariationSettings);
         int ttcIndex = array.getInt(R.styleable.FontFamilyFont_ttcIndex, 0);
diff --git a/core/java/android/content/res/ResourcesImpl.java b/core/java/android/content/res/ResourcesImpl.java
index dfa30a2..1d1eaf3 100644
--- a/core/java/android/content/res/ResourcesImpl.java
+++ b/core/java/android/content/res/ResourcesImpl.java
@@ -944,7 +944,8 @@
                 }
                 return Typeface.createFromResources(familyEntry, mAssets, file);
             }
-            return Typeface.createFromResources(mAssets, file, value.assetCookie);
+            return new Typeface.Builder(mAssets, file, false /* isAsset */, value.assetCookie)
+                    .build();
         } catch (XmlPullParserException e) {
             Log.e(TAG, "Failed to parse xml resource " + file, e);
         } catch (IOException e) {
diff --git a/core/java/android/net/INetdEventCallback.aidl b/core/java/android/net/INetdEventCallback.aidl
index 1e75bf4..4b1a08d 100644
--- a/core/java/android/net/INetdEventCallback.aidl
+++ b/core/java/android/net/INetdEventCallback.aidl
@@ -28,6 +28,11 @@
      * Reports a single DNS lookup function call.
      * This method must not block or perform long-running operations.
      *
+     * @param netId the ID of the network the lookup was performed on.
+     * @param eventType one of the EVENT_* constants in {@link INetdEventListener}.
+     * @param returnCode the return value of the query, may vary based on {@code eventType}. See
+     *        {@code getaddrinfo()}, {@code gethostbyaddr()} and {@code gethostbyname()} section in
+     *        bionic/libc/include/netdb.h.
      * @param hostname the name that was looked up.
      * @param ipAddresses (possibly a subset of) the IP addresses returned.
      *        At most {@link #DNS_REPORTED_IP_ADDRESSES_LIMIT} addresses are logged.
@@ -36,8 +41,8 @@
      * @param timestamp the timestamp at which the query was reported by netd.
      * @param uid the UID of the application that performed the query.
      */
-    void onDnsEvent(String hostname, in String[] ipAddresses, int ipAddressesCount, long timestamp,
-            int uid);
+    void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
+            in String[] ipAddresses, int ipAddressesCount, long timestamp, int uid);
 
     /**
      * Represents a private DNS validation success or failure.
diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java
index 483b764..0c4a0b3e 100644
--- a/core/java/android/os/Environment.java
+++ b/core/java/android/os/Environment.java
@@ -641,6 +641,13 @@
     public static String DIRECTORY_DOCUMENTS = "Documents";
 
     /**
+     * Standard directory in which to place screenshots that have been taken by
+     * the user. Typically used as a secondary directory under
+     * {@link #DIRECTORY_PICTURES}.
+     */
+    public static String DIRECTORY_SCREENSHOTS = "Screenshots";
+
+    /**
      * List of standard storage directories.
      * <p>
      * Each of its values have its own constant:
diff --git a/core/java/android/os/GraphicsEnvironment.java b/core/java/android/os/GraphicsEnvironment.java
index 0c56d48..ab048c5 100644
--- a/core/java/android/os/GraphicsEnvironment.java
+++ b/core/java/android/os/GraphicsEnvironment.java
@@ -170,10 +170,18 @@
 
                     String layers = coreSettings.getString(Settings.Global.GPU_DEBUG_LAYERS);
 
-                    Log.i(TAG, "Debug layer list: " + layers);
+                    Log.i(TAG, "Vulkan debug layer list: " + layers);
                     if (layers != null && !layers.isEmpty()) {
                         setDebugLayers(layers);
                     }
+
+                    String layersGLES =
+                            coreSettings.getString(Settings.Global.GPU_DEBUG_LAYERS_GLES);
+
+                    Log.i(TAG, "GLES debug layer list: " + layersGLES);
+                    if (layersGLES != null && !layersGLES.isEmpty()) {
+                        setDebugLayersGLES(layersGLES);
+                    }
                 }
             }
         }
@@ -424,6 +432,7 @@
     private static native int getCanLoadSystemLibraries();
     private static native void setLayerPaths(ClassLoader classLoader, String layerPaths);
     private static native void setDebugLayers(String layers);
+    private static native void setDebugLayersGLES(String layers);
     private static native void setDriverPath(String path);
     private static native void setAngleInfo(String path, String appPackage, String appPref,
                                             boolean devOptIn, FileDescriptor rulesFd,
diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java
index 1a84197..92b3169 100644
--- a/core/java/android/os/UserManager.java
+++ b/core/java/android/os/UserManager.java
@@ -936,6 +936,21 @@
     public static final String DISALLOW_AUTOFILL = "no_autofill";
 
     /**
+     * Specifies if the contents of a user's screen is not allowed to be captured for artificial
+     * intelligence purposes.
+     *
+     * <p>Device owner and profile owner can set this restriction. When it is set by device owner,
+     * only the target user will be affected.
+     *
+     * <p>The default value is <code>false</code>.
+     *
+     * @see DevicePolicyManager#addUserRestriction(ComponentName, String)
+     * @see DevicePolicyManager#clearUserRestriction(ComponentName, String)
+     * @see #getUserRestrictions()
+     */
+    public static final String DISALLOW_INTELLIGENCE_CAPTURE = "no_intelligence_capture";
+
+    /**
      * Specifies if user switching is blocked on the current user.
      *
      * <p> This restriction can only be set by the device owner, it will be applied to all users.
diff --git a/core/java/android/provider/FontsContract.java b/core/java/android/provider/FontsContract.java
index a1d1c57..76607e9 100644
--- a/core/java/android/provider/FontsContract.java
+++ b/core/java/android/provider/FontsContract.java
@@ -15,8 +15,6 @@
  */
 package android.provider;
 
-import static java.lang.annotation.RetentionPolicy.SOURCE;
-
 import android.annotation.IntDef;
 import android.annotation.IntRange;
 import android.annotation.NonNull;
@@ -25,22 +23,22 @@
 import android.content.ContentUris;
 import android.content.Context;
 import android.content.pm.PackageInfo;
-import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.PackageManager;
+import android.content.pm.PackageManager.NameNotFoundException;
 import android.content.pm.ProviderInfo;
 import android.content.pm.Signature;
 import android.database.Cursor;
 import android.graphics.Typeface;
+import android.graphics.fonts.Font;
+import android.graphics.fonts.FontFamily;
+import android.graphics.fonts.FontStyle;
 import android.graphics.fonts.FontVariationAxis;
 import android.net.Uri;
-import android.os.Bundle;
 import android.os.CancellationSignal;
 import android.os.Handler;
 import android.os.HandlerThread;
 import android.os.ParcelFileDescriptor;
 import android.os.Process;
-import android.os.ResultReceiver;
-import android.util.ArraySet;
 import android.util.Log;
 import android.util.LruCache;
 
@@ -49,7 +47,6 @@
 import com.android.internal.util.Preconditions;
 
 import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
@@ -64,11 +61,11 @@
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.concurrent.locks.Condition;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
 
 /**
  * Utility class to deal with Font ContentProviders.
@@ -636,7 +633,34 @@
         if (uriBuffer.isEmpty()) {
             return null;
         }
-        return new Typeface.Builder(fonts, uriBuffer).build();
+
+        FontFamily.Builder familyBuilder = null;
+        for (FontInfo fontInfo : fonts) {
+            final ByteBuffer buffer = uriBuffer.get(fontInfo.getUri());
+            if (buffer == null) {
+                continue;
+            }
+            try {
+                final Font font = new Font.Builder(buffer)
+                        .setWeight(fontInfo.getWeight())
+                        .setSlant(fontInfo.isItalic()
+                                ? FontStyle.FONT_SLANT_ITALIC : FontStyle.FONT_SLANT_UPRIGHT)
+                        .setTtcIndex(fontInfo.getTtcIndex())
+                        .setFontVariationSettings(fontInfo.getAxes())
+                        .build();
+                if (familyBuilder == null) {
+                    familyBuilder = new FontFamily.Builder(font);
+                } else {
+                    familyBuilder.addFont(font);
+                }
+            } catch (IOException e) {
+                continue;
+            }
+        }
+        if (familyBuilder == null) {
+            return null;
+        }
+        return new Typeface.CustomFallbackBuilder(familyBuilder.build()).build();
     }
 
     /**
diff --git a/core/java/android/provider/MediaStore.java b/core/java/android/provider/MediaStore.java
index 19b84f1..291891e 100644
--- a/core/java/android/provider/MediaStore.java
+++ b/core/java/android/provider/MediaStore.java
@@ -16,6 +16,7 @@
 
 package android.provider;
 
+import android.annotation.IntRange;
 import android.annotation.NonNull;
 import android.annotation.Nullable;
 import android.annotation.SdkConstant;
@@ -39,12 +40,16 @@
 import android.net.Uri;
 import android.os.Bundle;
 import android.os.CancellationSignal;
+import android.os.Environment;
 import android.os.OperationCanceledException;
+import android.os.ParcelFileDescriptor;
 import android.os.RemoteException;
+import android.os.UserHandle;
 import android.os.storage.StorageManager;
 import android.os.storage.StorageVolume;
 import android.os.storage.VolumeInfo;
 import android.service.media.CameraPrewarmService;
+import android.text.TextUtils;
 import android.util.ArrayMap;
 import android.util.ArraySet;
 import android.util.Log;
@@ -57,8 +62,8 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
-import java.util.ArrayList;
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
 
 /**
@@ -108,6 +113,15 @@
      */
     public static final String PARAM_DELETE_DATA = "deletedata";
 
+    /** {@hide} */
+    public static final String PARAM_PRIMARY = "primary";
+    /** {@hide} */
+    public static final String PARAM_SECONDARY = "secondary";
+    /** {@hide} */
+    public static final String PARAM_INCLUDE_PENDING = "includePending";
+    /** {@hide} */
+    public static final String PARAM_PROGRESS = "progress";
+
     /**
      * Activity Action: Launch a music player.
      * The activity should be able to play, browse, or manipulate music files stored on the device.
@@ -452,9 +466,200 @@
     public static final String UNKNOWN_STRING = "<unknown>";
 
     /**
+     * Update the given {@link Uri} to also include any pending media items from
+     * calls such as
+     * {@link ContentResolver#query(Uri, String[], Bundle, CancellationSignal)}.
+     * By default no pending items are returned.
+     *
+     * @see MediaColumns#IS_PENDING
+     */
+    public static @NonNull Uri setIncludePending(@NonNull Uri uri) {
+        return uri.buildUpon().appendQueryParameter(PARAM_INCLUDE_PENDING, "1").build();
+    }
+
+    /**
+     * Create a new pending media item using the given parameters. Pending items
+     * are expected to have a short lifetime, and owners should either
+     * {@link PendingSession#publish()} or {@link PendingSession#abandon()} a
+     * pending item within a few hours after first creating it.
+     *
+     * @return token which can be passed to {@link #openPending(Context, Uri)}
+     *         to work with this pending item.
+     */
+    public static @NonNull Uri createPending(@NonNull Context context,
+            @NonNull PendingParams params) {
+        final Uri.Builder builder = params.insertUri.buildUpon();
+        if (!TextUtils.isEmpty(params.primaryDirectory)) {
+            builder.appendQueryParameter(PARAM_PRIMARY, params.primaryDirectory);
+        }
+        if (!TextUtils.isEmpty(params.secondaryDirectory)) {
+            builder.appendQueryParameter(PARAM_SECONDARY, params.secondaryDirectory);
+        }
+        return context.getContentResolver().insert(builder.build(), params.insertValues);
+    }
+
+    /**
+     * Open a pending media item to make progress on it. You can open a pending
+     * item multiple times before finally calling either
+     * {@link PendingSession#publish()} or {@link PendingSession#abandon()}.
+     *
+     * @param uri token which was previously returned from
+     *            {@link #createPending(Context, PendingParams)}.
+     */
+    public static @NonNull PendingSession openPending(@NonNull Context context, @NonNull Uri uri) {
+        return new PendingSession(context, uri);
+    }
+
+    /**
+     * Parameters that describe a pending media item.
+     */
+    public static class PendingParams {
+        /** {@hide} */
+        public final Uri insertUri;
+        /** {@hide} */
+        public final ContentValues insertValues;
+        /** {@hide} */
+        public String primaryDirectory;
+        /** {@hide} */
+        public String secondaryDirectory;
+
+        /**
+         * Create parameters that describe a pending media item.
+         *
+         * @param insertUri the {@code content://} Uri where this pending item
+         *            should be inserted when finally published. For example, to
+         *            publish an image, use
+         *            {@link MediaStore.Images.Media#getContentUri(String)}.
+         */
+        public PendingParams(@NonNull Uri insertUri, @NonNull String displayName,
+                @NonNull String mimeType) {
+            this.insertUri = Objects.requireNonNull(insertUri);
+            final long now = System.currentTimeMillis() / 1000;
+            this.insertValues = new ContentValues();
+            this.insertValues.put(MediaColumns.DISPLAY_NAME, Objects.requireNonNull(displayName));
+            this.insertValues.put(MediaColumns.MIME_TYPE, Objects.requireNonNull(mimeType));
+            this.insertValues.put(MediaColumns.DATE_ADDED, now);
+            this.insertValues.put(MediaColumns.DATE_MODIFIED, now);
+            this.insertValues.put(MediaColumns.IS_PENDING, 1);
+        }
+
+        /**
+         * Optionally set the primary directory under which this pending item
+         * should be persisted. Only specific well-defined directories from
+         * {@link Environment} are allowed based on the media type being
+         * inserted.
+         * <p>
+         * For example, when creating pending {@link MediaStore.Images.Media}
+         * items, only {@link Environment#DIRECTORY_PICTURES} or
+         * {@link Environment#DIRECTORY_DCIM} are allowed.
+         * <p>
+         * You may leave this value undefined to store the media in a default
+         * location. For example, when this value is left undefined, pending
+         * {@link MediaStore.Audio.Media} items are stored under
+         * {@link Environment#DIRECTORY_MUSIC}.
+         */
+        public void setPrimaryDirectory(@Nullable String primaryDirectory) {
+            this.primaryDirectory = primaryDirectory;
+        }
+
+        /**
+         * Optionally set the secondary directory under which this pending item
+         * should be persisted. Any valid directory name is allowed.
+         * <p>
+         * You may leave this value undefined to store the media as a direct
+         * descendant of the {@link #setPrimaryDirectory(String)} location.
+         */
+        public void setSecondaryDirectory(@Nullable String secondaryDirectory) {
+            this.secondaryDirectory = secondaryDirectory;
+        }
+    }
+
+    /**
+     * Session actively working on a pending media item. Pending items are
+     * expected to have a short lifetime, and owners should either
+     * {@link PendingSession#publish()} or {@link PendingSession#abandon()} a
+     * pending item within a few hours after first creating it.
+     */
+    public static class PendingSession implements AutoCloseable {
+        /** {@hide} */
+        private final Context mContext;
+        /** {@hide} */
+        private final Uri mUri;
+
+        /** {@hide} */
+        public PendingSession(Context context, Uri uri) {
+            mContext = Objects.requireNonNull(context);
+            mUri = Objects.requireNonNull(uri);
+        }
+
+        /**
+         * Open the underlying file representing this media item. When a media
+         * item is successfully completed, you should
+         * {@link ParcelFileDescriptor#close()} and then {@link #publish()} it.
+         *
+         * @see #notifyProgress(int)
+         */
+        public @NonNull ParcelFileDescriptor open() throws FileNotFoundException {
+            return mContext.getContentResolver().openFileDescriptor(mUri, "rw");
+        }
+
+        /**
+         * Open the underlying file representing this media item. When a media
+         * item is successfully completed, you should
+         * {@link OutputStream#close()} and then {@link #publish()} it.
+         *
+         * @see #notifyProgress(int)
+         */
+        public @NonNull OutputStream openOutputStream() throws FileNotFoundException {
+            return mContext.getContentResolver().openOutputStream(mUri);
+        }
+
+        /**
+         * Notify of current progress on this pending media item. Gallery
+         * applications may choose to surface progress information of this
+         * pending item.
+         *
+         * @param progress a percentage between 0 and 100.
+         */
+        public void notifyProgress(@IntRange(from = 0, to = 100) int progress) {
+            final Uri withProgress = mUri.buildUpon()
+                    .appendQueryParameter(PARAM_PROGRESS, Integer.toString(progress)).build();
+            mContext.getContentResolver().notifyChange(withProgress, null, 0);
+        }
+
+        /**
+         * When this media item is successfully completed, call this method to
+         * publish and make the final item visible to the user.
+         *
+         * @return the final {@code content://} Uri representing the newly
+         *         published media.
+         */
+        public @NonNull Uri publish() {
+            final ContentValues values = new ContentValues();
+            values.put(MediaColumns.IS_PENDING, 0);
+            mContext.getContentResolver().update(mUri, values, null, null);
+            return mUri;
+        }
+
+        /**
+         * When this media item has failed to be completed, call this method to
+         * destroy the pending item record and any data related to it.
+         */
+        public void abandon() {
+            mContext.getContentResolver().delete(mUri, null, null);
+        }
+
+        @Override
+        public void close() {
+            // No resources to close, but at least we can inform people that no
+            // progress is being actively made.
+            notifyProgress(-1);
+        }
+    }
+
+    /**
      * Common fields for most MediaProvider tables
      */
-
     public interface MediaColumns extends BaseColumns {
         /**
          * Path to the file on disk.
@@ -552,6 +757,17 @@
         public static final String IS_DRM = "is_drm";
 
         /**
+         * Flag indicating if a media item is pending, and still being inserted
+         * by its owner.
+         * <p>
+         * Type: BOOLEAN
+         *
+         * @see MediaStore#createPending(Context, PendingParams)
+         * @see MediaStore#QUERY_ARG_INCLUDE_PENDING
+         */
+        public static final String IS_PENDING = "is_pending";
+
+        /**
          * The width of the image/video in pixels.
          */
         public static final String WIDTH = "width";
@@ -562,11 +778,13 @@
         public static final String HEIGHT = "height";
 
         /**
-         * Package that contributed this media.
-         * @hide
+         * Package name that contributed this media. The value may be
+         * {@code NULL} if ownership cannot be reliably determined.
+         * <p>
+         * Type: TEXT
          */
         public static final String OWNER_PACKAGE_NAME = "owner_package_name";
-     }
+    }
 
     /**
      * Media provider table containing an index of all files in the media storage,
@@ -2378,6 +2596,30 @@
         }
     }
 
+    /** {@hide} */
+    public static @NonNull File getVolumePath(@NonNull String volumeName)
+            throws FileNotFoundException {
+        Objects.requireNonNull(volumeName);
+
+        if (VOLUME_INTERNAL.equals(volumeName)) {
+            return Environment.getDataDirectory();
+        } else if (VOLUME_EXTERNAL.equals(volumeName)) {
+            return Environment.getExternalStorageDirectory();
+        }
+
+        final StorageManager sm = AppGlobals.getInitialApplication()
+                .getSystemService(StorageManager.class);
+        for (VolumeInfo vi : sm.getVolumes()) {
+            if (Objects.equals(vi.getFsUuid(), volumeName)) {
+                final File path = vi.getPathForUser(UserHandle.myUserId());
+                if (path == null) {
+                    throw new FileNotFoundException("Failed to find path for " + vi);
+                }
+            }
+        }
+        throw new FileNotFoundException("Failed to find path for " + volumeName);
+    }
+
     /**
      * Uri for querying the state of the media scanner.
      */
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 0ef56b0..eead3dff 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -819,6 +819,15 @@
             "android.settings.action.MANAGE_WRITE_SETTINGS";
 
     /**
+     * Activity Action: Show screen for controlling app usage properties for an app.
+     * Input: Intent's extra EXTRA_PACKAGE_NAME must specify the application package name.
+     * Output: Nothing.
+     */
+    @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
+    public static final String ACTION_APP_USAGE_SETTINGS =
+            "android.settings.action.APP_USAGE_SETTINGS";
+
+    /**
      * Activity Action: Show screen of details about a particular application.
      * <p>
      * In some cases, a matching Activity may not exist, so ensure you
@@ -11692,13 +11701,20 @@
         public static final String ANGLE_ENABLED_APP = "angle_enabled_app";
 
         /**
-         * Ordered GPU debug layer list
+         * Ordered GPU debug layer list for Vulkan
          * i.e. <layer1>:<layer2>:...:<layerN>
          * @hide
          */
         public static final String GPU_DEBUG_LAYERS = "gpu_debug_layers";
 
         /**
+         * Ordered GPU debug layer list for GLES
+         * i.e. <layer1>:<layer2>:...:<layerN>
+         * @hide
+         */
+        public static final String GPU_DEBUG_LAYERS_GLES = "gpu_debug_layers_gles";
+
+        /**
          * Addition app for GPU layer discovery
          * @hide
          */
diff --git a/core/java/android/service/intelligence/IntelligenceService.java b/core/java/android/service/intelligence/IntelligenceService.java
new file mode 100644
index 0000000..4b8825d
--- /dev/null
+++ b/core/java/android/service/intelligence/IntelligenceService.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.service.intelligence;
+
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.app.Service;
+import android.content.Intent;
+import android.view.intelligence.ContentCaptureEvent;
+
+import java.util.List;
+
+/**
+ * A service used to captures the content of the screen.
+ *
+ * <p>The data collected by this service can be analyzed and combined with other sources to provide
+ * contextual data in other areas of the system such as Autofill.
+ *
+ * @hide
+ */
+@SystemApi
+public abstract class IntelligenceService extends Service {
+
+    /**
+     * The {@link Intent} that must be declared as handled by the service.
+     * To be supported, the service must also require the
+     * {@link android.Manifest.permission#BIND_INTELLIGENCE_SERVICE} permission so
+     * that other applications can not abuse it.
+     */
+    public static final String SERVICE_INTERFACE =
+            "android.service.intelligence.IntelligenceService";
+
+    /**
+     * Creates a new interaction session.
+     *
+     * @param context interaction context
+     * @param sessionId the session's Id
+     */
+    public void onCreateInteractionSession(@NonNull InteractionContext context,
+            @NonNull InteractionSessionId sessionId) {}
+
+    /**
+     * Notifies the service of {@link ContentCaptureEvent events} associated with a content capture
+     * session.
+     *
+     * @param sessionId the session's Id
+     * @param events the events
+     */
+    public abstract void onContentCaptureEvent(@NonNull InteractionSessionId sessionId,
+            @NonNull List<ContentCaptureEvent> events);
+
+    /**
+     * Destroys the content capture session identified by the specified {@code sessionId}.
+     *
+     * @param sessionId the id of the session to destroy
+     */
+    public void onDestroyInteractionSession(@NonNull InteractionSessionId sessionId) {}
+}
diff --git a/core/java/android/service/intelligence/InteractionContext.java b/core/java/android/service/intelligence/InteractionContext.java
new file mode 100644
index 0000000..4d83820
--- /dev/null
+++ b/core/java/android/service/intelligence/InteractionContext.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.service.intelligence;
+
+import android.annotation.IntDef;
+import android.annotation.NonNull;
+import android.annotation.SystemApi;
+import android.app.TaskInfo;
+import android.content.ComponentName;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+// TODO(b/111276913): add javadocs / implement Parcelable / implement equals/hashcode/toString
+/** @hide */
+@SystemApi
+public final class InteractionContext implements Parcelable {
+
+    /**
+     * Flag used to indicate that the app explicitly disabled contents capture for the activity
+     * (using
+     * {@link android.view.intelligence.IntelligenceManager#disableContentCapture()}),
+     * in which case the service will just receive activity-level events.
+     */
+    public static final int FLAG_DISABLED_BY_APP = 0x1;
+
+    /**
+     * Flag used to indicate that the activity's window is tagged with
+     * {@link android.view.Display#FLAG_SECURE}, in which case the service will just receive
+     * activity-level events.
+     */
+    public static final int FLAG_DISABLED_BY_FLAG_SECURE = 0x2;
+
+    /** @hide */
+    @IntDef(flag = true, prefix = { "FLAG_" }, value = {
+            FLAG_DISABLED_BY_APP,
+            FLAG_DISABLED_BY_FLAG_SECURE
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    @interface ContextCreationFlags{}
+
+    /** @hide */
+    InteractionContext() {
+    }
+
+    /**
+     * Gets the id of the {@link TaskInfo task} associated with this context.
+     */
+    public int getTaskId() {
+        //TODO(b/111276913): implement
+        return 108;
+    }
+
+    /**
+     * Gets the activity associated with this context.
+     */
+    public @NonNull ComponentName getActivityComponent() {
+        //TODO(b/111276913): implement
+        return null;
+    }
+
+    /**
+     * Gets the ID of the display associated with this context, as defined by
+     * {G android.hardware.display.DisplayManager#getDisplay(int) DisplayManager.getDisplay()}.
+     */
+    public int getDisplayId() {
+        //TODO(b/111276913): implement
+        return 42;
+    }
+
+    /**
+     * Gets the flags associated with this context.
+     *
+     * @return any combination of {@link #FLAG_DISABLED_BY_FLAG_SECURE} and
+     * {@link #FLAG_DISABLED_BY_APP}.
+     */
+    public @ContextCreationFlags int getFlags() {
+        //TODO(b/111276913): implement
+        return 42;
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel parcel, int flags) {
+    }
+
+    public static final Parcelable.Creator<InteractionContext> CREATOR =
+            new Parcelable.Creator<InteractionContext>() {
+
+        @Override
+        public InteractionContext createFromParcel(Parcel parcel) {
+            // TODO(b/111276913): implement
+            return null;
+        }
+
+        @Override
+        public InteractionContext[] newArray(int size) {
+            return new InteractionContext[size];
+        }
+    };
+}
diff --git a/core/java/android/service/intelligence/InteractionSessionId.java b/core/java/android/service/intelligence/InteractionSessionId.java
new file mode 100644
index 0000000..4c9d706
--- /dev/null
+++ b/core/java/android/service/intelligence/InteractionSessionId.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.service.intelligence;
+
+import android.annotation.SystemApi;
+import android.os.Parcel;
+import android.os.Parcelable;
+
+// TODO(b/111276913): add javadocs / implement equals/hashcode/string
+/** @hide */
+@SystemApi
+public final class InteractionSessionId implements Parcelable {
+
+    /** @hide */
+    public InteractionSessionId() {
+    }
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel parcel, int flags) {
+    }
+
+    public static final Parcelable.Creator<InteractionSessionId> CREATOR =
+            new Parcelable.Creator<InteractionSessionId>() {
+
+        @Override
+        public InteractionSessionId createFromParcel(Parcel parcel) {
+            // TODO(b/111276913): implement
+            return null;
+        }
+
+        @Override
+        public InteractionSessionId[] newArray(int size) {
+            return new InteractionSessionId[size];
+        }
+    };
+}
diff --git a/core/java/android/util/ArraySet.java b/core/java/android/util/ArraySet.java
index d74a0fe..4bd43d0 100644
--- a/core/java/android/util/ArraySet.java
+++ b/core/java/android/util/ArraySet.java
@@ -16,14 +16,17 @@
 
 package android.util;
 
+import android.annotation.TestApi;
+import android.annotation.UnsupportedAppUsage;
+
 import libcore.util.EmptyArray;
 
-import android.annotation.UnsupportedAppUsage;
 import java.lang.reflect.Array;
 import java.util.Collection;
 import java.util.Iterator;
 import java.util.Map;
 import java.util.Set;
+import java.util.function.Predicate;
 
 /**
  * ArraySet is a generic set data structure that is designed to be more memory efficient than a
@@ -357,6 +360,22 @@
      * @return Returns the value stored at the given index.
      */
     public E valueAt(int index) {
+        if (index >= mSize) {
+            // The array might be slightly bigger than mSize, in which case, indexing won't fail.
+            throw new ArrayIndexOutOfBoundsException(index);
+        }
+        return valueAtUnchecked(index);
+    }
+
+    /**
+     * Returns the value at the given index in the array without checking that the index is within
+     * bounds. This allows testing values at the end of the internal array, outside of the
+     * [0, mSize) bounds.
+     *
+     * @hide
+     */
+    @TestApi
+    public E valueAtUnchecked(int index) {
         return (E) mArray[index];
     }
 
@@ -491,26 +510,40 @@
         return false;
     }
 
+    /** Returns true if the array size should be decreased. */
+    private boolean shouldShrink() {
+        return mHashes.length > (BASE_SIZE * 2) && mSize < mHashes.length / 3;
+    }
+
+    /**
+     * Returns the new size the array should have. Is only valid if {@link #shouldShrink} returns
+     * true.
+     */
+    private int getNewShrunkenSize() {
+        // We don't allow it to shrink smaller than (BASE_SIZE*2) to avoid flapping between that
+        // and BASE_SIZE.
+        return mSize > (BASE_SIZE * 2) ? (mSize + (mSize >> 1)) : (BASE_SIZE * 2);
+    }
+
     /**
      * Remove the key/value mapping at the given index.
      * @param index The desired index, must be between 0 and {@link #size()}-1.
      * @return Returns the value that was stored at this index.
      */
     public E removeAt(int index) {
+        if (index >= mSize) {
+            // The array might be slightly bigger than mSize, in which case, indexing won't fail.
+            throw new ArrayIndexOutOfBoundsException(index);
+        }
         final Object old = mArray[index];
         if (mSize <= 1) {
             // Now empty.
             if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to 0");
-            freeArrays(mHashes, mArray, mSize);
-            mHashes = EmptyArray.INT;
-            mArray = EmptyArray.OBJECT;
-            mSize = 0;
+            clear();
         } else {
-            if (mHashes.length > (BASE_SIZE * 2) && mSize < mHashes.length / 3) {
-                // Shrunk enough to reduce size of arrays.  We don't allow it to
-                // shrink smaller than (BASE_SIZE*2) to avoid flapping between
-                // that and BASE_SIZE.
-                final int n = mSize > (BASE_SIZE * 2) ? (mSize + (mSize >> 1)) : (BASE_SIZE * 2);
+            if (shouldShrink()) {
+                // Shrunk enough to reduce size of arrays.
+                final int n = getNewShrunkenSize();
 
                 if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to " + n);
 
@@ -568,6 +601,62 @@
     }
 
     /**
+     * Removes all values that satisfy the predicate. This implementation avoids using the
+     * {@link #iterator()}.
+     *
+     * @param filter A predicate which returns true for elements to be removed
+     */
+    @Override
+    public boolean removeIf(Predicate<? super E> filter) {
+        if (mSize == 0) {
+            return false;
+        }
+
+        // Intentionally not using removeAt() to avoid unnecessary intermediate resizing.
+
+        int replaceIndex = 0;
+        int numRemoved = 0;
+        for (int i = 0; i < mSize; ++i) {
+            if (filter.test((E) mArray[i])) {
+                numRemoved++;
+            } else {
+                if (replaceIndex != i) {
+                    mArray[replaceIndex] = mArray[i];
+                    mHashes[replaceIndex] = mHashes[i];
+                }
+                replaceIndex++;
+            }
+        }
+
+        if (numRemoved == 0) {
+            return false;
+        } else if (numRemoved == mSize) {
+            clear();
+            return true;
+        }
+
+        mSize -= numRemoved;
+        if (shouldShrink()) {
+            // Shrunk enough to reduce size of arrays.
+            final int n = getNewShrunkenSize();
+            final int[] ohashes = mHashes;
+            final Object[] oarray = mArray;
+            allocArrays(n);
+
+            System.arraycopy(ohashes, 0, mHashes, 0, mSize);
+            System.arraycopy(oarray, 0, mArray, 0, mSize);
+        } else {
+            // Null out values at the end of the array. Not doing it in the loop above to avoid
+            // writing twice to the same index or writing unnecessarily if the array would have been
+            // discarded anyway.
+            for (int i = mSize; i < mArray.length; ++i) {
+                mArray[i] = null;
+            }
+        }
+        return true;
+    }
+
+    /**
      * Return the number of items in this array map.
      */
     @Override
diff --git a/core/java/android/view/TouchDelegate.java b/core/java/android/view/TouchDelegate.java
index 6fb32e3..bef9f07 100644
--- a/core/java/android/view/TouchDelegate.java
+++ b/core/java/android/view/TouchDelegate.java
@@ -103,13 +103,13 @@
     }
 
     /**
-     * Will forward touch events to the delegate view if the event is within the bounds
+     * Forward touch events to the delegate view if the event is within the bounds
      * specified in the constructor.
      *
      * @param event The touch event to forward
-     * @return True if the event was forwarded to the delegate, false otherwise.
+     * @return True if the event was consumed by the delegate, false otherwise.
      */
-    public boolean onTouchEvent(MotionEvent event) {
+    public boolean onTouchEvent(@NonNull MotionEvent event) {
         int x = (int)event.getX();
         int y = (int)event.getY();
         boolean sendToDelegate = false;
@@ -139,18 +139,65 @@
                 break;
         }
         if (sendToDelegate) {
-            final View delegateView = mDelegateView;
-
             if (hit) {
                 // Offset event coordinates to be inside the target view
-                event.setLocation(delegateView.getWidth() / 2, delegateView.getHeight() / 2);
+                event.setLocation(mDelegateView.getWidth() / 2, mDelegateView.getHeight() / 2);
             } else {
                 // Offset event coordinates to be outside the target view (in case it does
                 // something like tracking pressed state)
                 int slop = mSlop;
                 event.setLocation(-(slop * 2), -(slop * 2));
             }
-            handled = delegateView.dispatchTouchEvent(event);
+            handled = mDelegateView.dispatchTouchEvent(event);
+        }
+        return handled;
+    }
+
+    /**
+     * Forward hover events to the delegate view if the event is within the bounds
+     * specified in the constructor and touch exploration is enabled.
+     *
+     * @param event The hover event to forward
+     * @return True if the event was consumed by the delegate, false otherwise.
+     *
+     * @see android.view.accessibility.AccessibilityManager#isTouchExplorationEnabled
+     */
+    public boolean onTouchExplorationHoverEvent(@NonNull MotionEvent event) {
+        if (mBounds == null) {
+            return false;
+        }
+
+        final int x = (int) event.getX();
+        final int y = (int) event.getY();
+        boolean hit = true;
+        boolean handled = false;
+
+        final boolean isInbound = mBounds.contains(x, y);
+        switch (event.getActionMasked()) {
+            case MotionEvent.ACTION_HOVER_ENTER:
+                mDelegateTargeted = isInbound;
+                break;
+            case MotionEvent.ACTION_HOVER_MOVE:
+                if (isInbound) {
+                    mDelegateTargeted = true;
+                } else {
+                    // delegated previously
+                    if (mDelegateTargeted && !mSlopBounds.contains(x, y)) {
+                        hit = false;
+                    }
+                }
+                break;
+            case MotionEvent.ACTION_HOVER_EXIT:
+                mDelegateTargeted = true;
+                break;
+        }
+        if (mDelegateTargeted) {
+            if (hit) {
+                event.setLocation(mDelegateView.getWidth() / 2, mDelegateView.getHeight() / 2);
+            } else {
+                mDelegateTargeted = false;
+            }
+            handled = mDelegateView.dispatchHoverEvent(event);
         }
         return handled;
     }
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 1493cd7..43fcce3 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -12830,6 +12830,15 @@
     }
 
     /**
+     * Returns true if the given point, in local coordinates, is inside the hovered child.
+     *
+     * @hide
+     */
+    protected boolean pointInHoveredChild(MotionEvent event) {
+        return false;
+    }
+
+    /**
      * Dispatch a generic motion event to the view under the first pointer.
      * <p>
      * Do not call this method directly.
@@ -13584,6 +13593,17 @@
      * @see #onHoverChanged
      */
     public boolean onHoverEvent(MotionEvent event) {
+        // Explore by touch should dispatch events to children under pointer first if any before
+        // dispatching to TouchDelegate. For children non-hoverable that will not consume events,
+        // it should also not delegate when they got the pointer hovered.
+        if (mTouchDelegate != null && !pointInHoveredChild(event)) {
+            final AccessibilityManager manager = AccessibilityManager.getInstance(mContext);
+            if (manager.isEnabled() && manager.isTouchExplorationEnabled()
+                    && mTouchDelegate.onTouchExplorationHoverEvent(event)) {
+                return true;
+            }
+        }
+
         // The root view may receive hover (or touch) events that are outside the bounds of
         // the window.  This code ensures that we only send accessibility events for
         // hovers that are actually within the bounds of the root view.
@@ -13598,7 +13618,7 @@
             }
         } else {
             if (action == MotionEvent.ACTION_HOVER_EXIT
-                    || (action == MotionEvent.ACTION_MOVE
+                    || (action == MotionEvent.ACTION_HOVER_MOVE
                             && !pointInView(event.getX(), event.getY()))) {
                 mSendingHoverAccessibilityEvents = false;
                 sendAccessibilityHoverEvent(AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
@@ -14710,7 +14730,7 @@
      */
     public float getCameraDistance() {
         final float dpi = mResources.getDisplayMetrics().densityDpi;
-        return -(mRenderNode.getCameraDistance() * dpi);
+        return mRenderNode.getCameraDistance() * dpi;
     }
 
     /**
@@ -14756,7 +14776,7 @@
         final float dpi = mResources.getDisplayMetrics().densityDpi;
 
         invalidateViewProperty(true, false);
-        mRenderNode.setCameraDistance(-Math.abs(distance) / dpi);
+        mRenderNode.setCameraDistance(Math.abs(distance) / dpi);
         invalidateViewProperty(false, false);
 
         invalidateParentIfNeededAndWasQuickRejected();
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 58febb05..1e91aa8 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -2383,6 +2383,16 @@
         return mFirstHoverTarget != null;
     }
 
+    /** @hide */
+    @Override
+    protected boolean pointInHoveredChild(MotionEvent event) {
+        if (mFirstHoverTarget != null) {
+            return isTransformedTouchPointInView(event.getX(), event.getY(),
+                mFirstHoverTarget.child, null);
+        }
+        return false;
+    }
+
     @Override
     public void addChildrenForAccessibility(ArrayList<View> outChildren) {
         if (getAccessibilityNodeProvider() != null) {
diff --git a/core/java/android/view/ViewRootImpl.java b/core/java/android/view/ViewRootImpl.java
index 4876148..dd1f640 100644
--- a/core/java/android/view/ViewRootImpl.java
+++ b/core/java/android/view/ViewRootImpl.java
@@ -6877,7 +6877,7 @@
         RenderNode renderNode = view.mRenderNode;
         info[0]++;
         if (renderNode != null) {
-            info[1] += renderNode.getDebugSize();
+            info[1] += renderNode.computeApproximateMemoryUsage();
         }
 
         if (view instanceof ViewGroup) {
diff --git a/core/java/android/view/intelligence/ContentCaptureEvent.java b/core/java/android/view/intelligence/ContentCaptureEvent.java
new file mode 100644
index 0000000..b8330e5
--- /dev/null
+++ b/core/java/android/view/intelligence/ContentCaptureEvent.java
@@ -0,0 +1,176 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.view.intelligence;
+
+import android.annotation.IntDef;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.view.autofill.AutofillId;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+// TODO(b/111276913): add javadocs / implement Parcelable / implement
+/** @hide */
+@SystemApi
+public final class ContentCaptureEvent implements Parcelable {
+
+    /**
+     * Called when the activity is started.
+     */
+    public static final int TYPE_ACTIVITY_STARTED  = 1;
+
+    /**
+     * Called when the activity is resumed.
+     */
+    public static final int TYPE_ACTIVITY_RESUMED = 2;
+
+    /**
+     * Called when the activity is paused.
+     */
+    public static final int TYPE_ACTIVITY_PAUSED = 3;
+
+    /**
+     * Called when the activity is stopped.
+     */
+    public static final int TYPE_ACTIVITY_STOPPED  = 4;
+
+    /**
+     * Called when a node has been added to the screen and is visible to the user.
+     *
+     * <p>The metadata of the node is available through {@link #getViewNode()}.
+     */
+    public static final int TYPE_VIEW_ADDED = 5;
+
+    /**
+     * Called when a node has been removed from the screen and is not visible to the user anymore.
+     *
+     * <p>The id of the node is available through {@link #getId()}.
+     */
+    public static final int TYPE_VIEW_REMOVED = 6;
+
+    /**
+     * Called when the text of a node has been changed.
+     *
+     * <p>The id of the node is available through {@link #getId()}, and the new text is
+     * available through {@link #getText()}.
+     */
+    public static final int TYPE_VIEW_TEXT_CHANGED = 7;
+
+    // TODO(b/111276913): add event to indicate when FLAG_SECURE was changed?
+
+    /** @hide */
+    @IntDef(prefix = { "TYPE_" }, value = {
+            TYPE_ACTIVITY_STARTED,
+            TYPE_ACTIVITY_PAUSED,
+            TYPE_ACTIVITY_RESUMED,
+            TYPE_ACTIVITY_STOPPED,
+            TYPE_VIEW_ADDED,
+            TYPE_VIEW_REMOVED,
+            TYPE_VIEW_TEXT_CHANGED
+    })
+    @Retention(RetentionPolicy.SOURCE)
+    @interface EventType{}
+
+    /** @hide */
+    ContentCaptureEvent() {
+    }
+
+    /**
+     * Gets the type of the event.
+     *
+     * @return one of {@link #TYPE_ACTIVITY_STARTED}, {@link #TYPE_ACTIVITY_RESUMED},
+     * {@link #TYPE_ACTIVITY_PAUSED}, {@link #TYPE_ACTIVITY_STOPPED},
+     * {@link #TYPE_VIEW_ADDED}, {@link #TYPE_VIEW_REMOVED}, or {@link #TYPE_VIEW_TEXT_CHANGED}.
+     */
+    public @EventType int getType() {
+        return 42;
+    }
+
+    /**
+     * Gets when the event was generated, in ms.
+     */
+    public long getEventTime() {
+        return 48151623;
+    }
+
+    /**
+     * Gets optional flags associated with the event.
+     *
+     * @return either {@code 0} or
+     * {@link android.view.intelligence.IntelligenceManager#FLAG_USER_INPUT}.
+     */
+    public int getFlags() {
+        return 0;
+    }
+
+    /**
+     * Gets the whole metadata of the node associated with the event.
+     *
+     * <p>Only set on {@link #TYPE_VIEW_ADDED} events.
+     */
+    @Nullable
+    public ViewNode getViewNode() {
+        return null;
+    }
+
+    /**
+     * Gets the {@link AutofillId} of the node associated with the event.
+     *
+     * <p>Only set on {@link #TYPE_VIEW_REMOVED} and {@link #TYPE_VIEW_TEXT_CHANGED} events.
+     */
+    @Nullable
+    public AutofillId getId() {
+        return null;
+    }
+
+    /**
+     * Gets the current text of the node associated with the event.
+     *
+     * <p>Only set on {@link #TYPE_VIEW_TEXT_CHANGED} events.
+     */
+    @Nullable
+    public CharSequence getText() {
+        return null;
+    }
+
+
+    @Override
+    public int describeContents() {
+        return 0;
+    }
+
+    @Override
+    public void writeToParcel(Parcel parcel, int flags) {
+    }
+
+    public static final Parcelable.Creator<ContentCaptureEvent> CREATOR =
+            new Parcelable.Creator<ContentCaptureEvent>() {
+
+        @Override
+        public ContentCaptureEvent createFromParcel(Parcel parcel) {
+            // TODO(b/111276913): implement
+            return null;
+        }
+
+        @Override
+        public ContentCaptureEvent[] newArray(int size) {
+            return new ContentCaptureEvent[size];
+        }
+    };
+}
diff --git a/core/java/android/view/intelligence/IntelligenceManager.java b/core/java/android/view/intelligence/IntelligenceManager.java
new file mode 100644
index 0000000..cbe73ef
--- /dev/null
+++ b/core/java/android/view/intelligence/IntelligenceManager.java
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.view.intelligence;
+
+import android.annotation.NonNull;
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.content.ComponentName;
+import android.content.Context;
+
+import com.android.internal.util.Preconditions;
+
+import java.util.Set;
+
+/**
+ * TODO(b/111276913): add javadocs / implement / add SystemService / PackageFeature
+ */
+public final class IntelligenceManager {
+
+    /**
+     * Used to indicate that a text change was caused by user input (for example, through IME).
+     */
+    //TODO(b/111276913): link to notifyTextChanged() method once available
+    public static final int FLAG_USER_INPUT = 0x1;
+
+    private final Context mContext;
+
+    /** @hide */
+    public IntelligenceManager(@NonNull Context context) {
+        mContext = Preconditions.checkNotNull(context, "context cannot be null");
+    }
+
+    /**
+     * Returns the component name of the {@link android.service.intelligence.IntelligenceService}
+     * that is enabled for the current user.
+     */
+    @Nullable
+    public ComponentName getIntelligenceServiceComponentName() {
+        //TODO(b/111276913): implement
+        return null;
+    }
+
+    /**
+     * Checks whether contents capture is enabled for this activity.
+     */
+    public boolean isContentCaptureEnabled() {
+        //TODO(b/111276913): implement
+        return false;
+    }
+
+    /**
+     * Called by apps to disable content capture.
+     *
+     * <p><b>Note: </b> this call is not persisted accross reboots, so apps should typically call
+     * it on {@link android.app.Activity#onCreate(android.os.Bundle, android.os.PersistableBundle)}.
+     */
+    public void disableContentCapture() {
+    }
+
+    /**
+     * Called by the the service {@link android.service.intelligence.IntelligenceService}
+     * to define whether content capture should be enabled for activities with such
+     * {@link android.content.ComponentName}.
+     *
+     * <p>Useful to blacklist a particular activity.
+     *
+     * @throws UnsupportedOperationException if not called by the UID that owns the
+     * {@link android.service.intelligence.IntelligenceService} associated with the
+     * current user.
+     *
+     * @hide
+     */
+    @SystemApi
+    public void setActivityContentCaptureEnabled(@NonNull ComponentName activity,
+            boolean enabled) {
+        //TODO(b/111276913): implement
+    }
+
+    /**
+     * Called by the the service {@link android.service.intelligence.IntelligenceService}
+     * to define whether content capture should be enabled for activities of the app with such
+     * {@code packageName}.
+     *
+     * <p>Useful to blacklist any activity from a particular app.
+     *
+     * @throws UnsupportedOperationException if not called by the UID that owns the
+     * {@link android.service.intelligence.IntelligenceService} associated with the
+     * current user.
+     *
+     * @hide
+     */
+    @SystemApi
+    public void setPackageContentCaptureEnabled(@NonNull String packageName, boolean enabled) {
+        //TODO(b/111276913): implement
+    }
+
+    /**
+     * Gets the activities where content capture was disabled by
+     * {@link #setActivityContentCaptureEnabled(ComponentName, boolean)}.
+     *
+     * @throws UnsupportedOperationException if not called by the UID that owns the
+     * {@link android.service.intelligence.IntelligenceService} associated with the
+     * current user.
+     *
+     * @hide
+     */
+    @SystemApi
+    @NonNull
+    public Set<ComponentName> getContentCaptureDisabledActivities() {
+        //TODO(b/111276913): implement
+        return null;
+    }
+
+    /**
+     * Gets the apps where content capture was disabled by
+     * {@link #setPackageContentCaptureEnabled(String, boolean)}.
+     *
+     * @throws UnsupportedOperationException if not called by the UID that owns the
+     * {@link android.service.intelligence.IntelligenceService} associated with the
+     * current user.
+     *
+     * @hide
+     */
+    @SystemApi
+    @NonNull
+    public Set<String> getContentCaptureDisabledPackages() {
+        //TODO(b/111276913): implement
+        return null;
+    }
+}
diff --git a/core/java/android/view/intelligence/ViewNode.java b/core/java/android/view/intelligence/ViewNode.java
new file mode 100644
index 0000000..357ecf5
--- /dev/null
+++ b/core/java/android/view/intelligence/ViewNode.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package android.view.intelligence;
+
+import android.annotation.Nullable;
+import android.annotation.SystemApi;
+import android.app.assist.AssistStructure;
+import android.view.autofill.AutofillId;
+
+//TODO(b/111276913): add javadocs / implement Parcelable / implement
+//TODO(b/111276913): for now it's extending ViewNode directly as it needs most of its properties,
+// but it might be better to create a common, abstract android.view.ViewNode class that both extend
+// instead
+/** @hide */
+@SystemApi
+public final class ViewNode extends AssistStructure.ViewNode {
+
+    /** @hide */
+    public ViewNode() {
+    }
+
+    /**
+     * Returns the {@link AutofillId} of this view's parent, if the parent is also part of the
+     * screen observation tree.
+     */
+    @Nullable
+    public AutofillId getParentAutofillId() {
+        //TODO(b/111276913): implement
+        return null;
+    }
+}
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index feef853..f96f088 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -48,6 +48,7 @@
 import android.graphics.RenderNode;
 import android.graphics.drawable.ColorDrawable;
 import android.graphics.drawable.Drawable;
+import android.os.Build;
 import android.os.Bundle;
 import android.os.LocaleList;
 import android.os.Parcel;
@@ -310,12 +311,12 @@
 
     Drawable mDrawableForCursor = null;
 
-    @UnsupportedAppUsage
-    private Drawable mSelectHandleLeft;
-    @UnsupportedAppUsage
-    private Drawable mSelectHandleRight;
-    @UnsupportedAppUsage
-    private Drawable mSelectHandleCenter;
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
+    Drawable mSelectHandleLeft;
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
+    Drawable mSelectHandleRight;
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
+    Drawable mSelectHandleCenter;
 
     // Global listener that detects changes in the global position of the TextView
     private PositionListener mPositionListener;
@@ -3927,7 +3928,6 @@
                 SelectionModifierCursorController selectionController = getSelectionController();
                 if (selectionController.mStartHandle == null) {
                     // As these are for initializing selectionController, hide() must be called.
-                    selectionController.initDrawables();
                     selectionController.initHandles();
                     selectionController.hide();
                 }
@@ -4495,13 +4495,11 @@
             mContainer.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
             mContainer.setContentView(this);
 
-            mDrawableLtr = drawableLtr;
-            mDrawableRtl = drawableRtl;
+            setDrawables(drawableLtr, drawableRtl);
+
             mMinSize = mTextView.getContext().getResources().getDimensionPixelSize(
                     com.android.internal.R.dimen.text_handle_min_size);
 
-            updateDrawable();
-
             final int handleHeight = getPreferredHeight();
             mTouchOffsetY = -0.3f * handleHeight;
             mIdealVerticalOffset = 0.7f * handleHeight;
@@ -4511,9 +4509,14 @@
             return mIdealVerticalOffset;
         }
 
-        protected void updateDrawable() {
-            if (mIsDragging) {
-                // Don't update drawable during dragging.
+        void setDrawables(final Drawable drawableLtr, final Drawable drawableRtl) {
+            mDrawableLtr = drawableLtr;
+            mDrawableRtl = drawableRtl;
+            updateDrawable(true /* updateDrawableWhenDragging */);
+        }
+
+        protected void updateDrawable(final boolean updateDrawableWhenDragging) {
+            if (!updateDrawableWhenDragging && mIsDragging) {
                 return;
             }
             final Layout layout = mTextView.getLayout();
@@ -5030,7 +5033,7 @@
                     // Fall through.
                 case MotionEvent.ACTION_CANCEL:
                     mIsDragging = false;
-                    updateDrawable();
+                    updateDrawable(false /* updateDrawableWhenDragging */);
                     break;
             }
             return true;
@@ -5315,7 +5318,7 @@
                 Selection.setSelection((Spannable) mTextView.getText(),
                         mTextView.getSelectionStart(), offset);
             }
-            updateDrawable();
+            updateDrawable(false /* updateDrawableWhenDragging */);
             if (mTextActionMode != null) {
                 invalidateActionMode();
             }
@@ -5717,16 +5720,22 @@
         }
 
         private InsertionHandleView getHandle() {
-            if (mSelectHandleCenter == null) {
-                mSelectHandleCenter = mTextView.getContext().getDrawable(
-                        mTextView.mTextSelectHandleRes);
-            }
             if (mHandle == null) {
+                loadHandleDrawables(false /* overwrite */);
                 mHandle = new InsertionHandleView(mSelectHandleCenter);
             }
             return mHandle;
         }
 
+        private void reloadHandleDrawable() {
+            if (mHandle == null) {
+                // No need to reload, the potentially new drawable will
+                // be used when the handle is created.
+                return;
+            }
+            mHandle.setDrawables(mSelectHandleCenter, mSelectHandleCenter);
+        }
+
         @Override
         public void onDetached() {
             final ViewTreeObserver observer = mTextView.getViewTreeObserver();
@@ -5790,21 +5799,10 @@
             if (mTextView.isInBatchEditMode()) {
                 return;
             }
-            initDrawables();
+            loadHandleDrawables(false /* overwrite */);
             initHandles();
         }
 
-        private void initDrawables() {
-            if (mSelectHandleLeft == null) {
-                mSelectHandleLeft = mTextView.getContext().getDrawable(
-                        mTextView.mTextSelectHandleLeftRes);
-            }
-            if (mSelectHandleRight == null) {
-                mSelectHandleRight = mTextView.getContext().getDrawable(
-                        mTextView.mTextSelectHandleRightRes);
-            }
-        }
-
         private void initHandles() {
             // Lazy object creation has to be done before updatePosition() is called.
             if (mStartHandle == null) {
@@ -5824,6 +5822,16 @@
             hideInsertionPointCursorController();
         }
 
+        private void reloadHandleDrawables() {
+            if (mStartHandle == null) {
+                // No need to reload, the potentially new drawables will
+                // be used when the handles are created.
+                return;
+            }
+            mStartHandle.setDrawables(mSelectHandleLeft, mSelectHandleRight);
+            mEndHandle.setDrawables(mSelectHandleRight, mSelectHandleLeft);
+        }
+
         public void hide() {
             if (mStartHandle != null) mStartHandle.hide();
             if (mEndHandle != null) mEndHandle.hide();
@@ -6184,6 +6192,32 @@
         }
     }
 
+    /**
+     * Loads the insertion and selection handle Drawables from TextView. If the handle
+     * drawables are already loaded, do not overwrite them unless the method parameter
+     * is set to true. This logic is required to avoid overwriting Drawables assigned
+     * to mSelectHandle[Center/Left/Right] by developers using reflection, unless they
+     * explicitly call the setters in TextView.
+     *
+     * @param overwrite whether to overwrite already existing nonnull Drawables
+     */
+    void loadHandleDrawables(final boolean overwrite) {
+        if (mSelectHandleCenter == null || overwrite) {
+            mSelectHandleCenter = mTextView.getTextSelectHandle();
+            if (hasInsertionController()) {
+                getInsertionController().reloadHandleDrawable();
+            }
+        }
+
+        if (mSelectHandleLeft == null || mSelectHandleRight == null || overwrite) {
+            mSelectHandleLeft = mTextView.getTextSelectHandleLeft();
+            mSelectHandleRight = mTextView.getTextSelectHandleRight();
+            if (hasSelectionController()) {
+                getSelectionController().reloadHandleDrawables();
+            }
+        }
+    }
+
     private class CorrectionHighlighter {
         private final Path mPath = new Path();
         private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 66809db..572670f 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -67,6 +67,7 @@
 import android.graphics.fonts.FontVariationAxis;
 import android.icu.text.DecimalFormatSymbols;
 import android.os.AsyncTask;
+import android.os.Build;
 import android.os.Build.VERSION_CODES;
 import android.os.Bundle;
 import android.os.LocaleList;
@@ -799,17 +800,21 @@
     // they are defined by the TextView's style and are theme-dependent.
     @UnsupportedAppUsage
     int mCursorDrawableRes;
-    // These six fields, could be moved to Editor, since we know their default values and we
-    // could condition the creation of the Editor to a non standard value. This is however
-    // brittle since the hardcoded values here (such as
-    // com.android.internal.R.drawable.text_select_handle_left) would have to be updated if the
-    // default style is modified.
-    @UnsupportedAppUsage
+    // Note: this might be stale if setTextSelectHandleLeft is used. We could simplify the code
+    // by removing it, but we would break apps targeting <= P that use it by reflection.
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
     int mTextSelectHandleLeftRes;
-    @UnsupportedAppUsage
+    private Drawable mTextSelectHandleLeft;
+    // Note: this might be stale if setTextSelectHandleRight is used. We could simplify the code
+    // by removing it, but we would break apps targeting <= P that use it by reflection.
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
     int mTextSelectHandleRightRes;
-    @UnsupportedAppUsage
+    private Drawable mTextSelectHandleRight;
+    // Note: this might be stale if setTextSelectHandle is used. We could simplify the code
+    // by removing it, but we would break apps targeting <= P that use it by reflection.
+    @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
     int mTextSelectHandleRes;
+    private Drawable mTextSelectHandle;
     int mTextEditSuggestionItemLayout;
     int mTextEditSuggestionContainerLayout;
     int mTextEditSuggestionHighlightStyle;
@@ -3477,6 +3482,175 @@
     }
 
     /**
+     * Sets the Drawable corresponding to the selection handle used for
+     * positioning the cursor within text. The Drawable defaults to the value
+     * of the textSelectHandle attribute.
+     * Note that any change applied to the handle Drawable will not be visible
+     * until the handle is hidden and then drawn again.
+     *
+     * @see #setTextSelectHandle(int)
+     * @attr ref android.R.styleable#TextView_textSelectHandle
+     */
+    @android.view.RemotableViewMethod
+    public void setTextSelectHandle(@NonNull Drawable textSelectHandle) {
+        Preconditions.checkNotNull(textSelectHandle,
+                "The text select handle should not be null.");
+        mTextSelectHandle = textSelectHandle;
+        mTextSelectHandleRes = 0;
+        if (mEditor != null) {
+            mEditor.loadHandleDrawables(true /* overwrite */);
+        }
+    }
+
+    /**
+     * Sets the Drawable corresponding to the selection handle used for
+     * positioning the cursor within text. The Drawable defaults to the value
+     * of the textSelectHandle attribute.
+     * Note that any change applied to the handle Drawable will not be visible
+     * until the handle is hidden and then drawn again.
+     *
+     * @see #setTextSelectHandle(Drawable)
+     * @attr ref android.R.styleable#TextView_textSelectHandle
+     */
+    @android.view.RemotableViewMethod
+    public void setTextSelectHandle(@DrawableRes int textSelectHandle) {
+        Preconditions.checkArgumentPositive(textSelectHandle,
+                "The text select handle should be a valid drawable resource id.");
+        setTextSelectHandle(mContext.getDrawable(textSelectHandle));
+    }
+
+    /**
+     * Returns the Drawable corresponding to the selection handle used
+     * for positioning the cursor within text.
+     * Note that any change applied to the handle Drawable will not be visible
+     * until the handle is hidden and then drawn again.
+     *
+     * @return the text select handle drawable
+     *
+     * @see #setTextSelectHandle(Drawable)
+     * @see #setTextSelectHandle(int)
+     * @attr ref android.R.styleable#TextView_textSelectHandle
+     */
+    @Nullable public Drawable getTextSelectHandle() {
+        if (mTextSelectHandle == null && mTextSelectHandleRes != 0) {
+            mTextSelectHandle = mContext.getDrawable(mTextSelectHandleRes);
+        }
+        return mTextSelectHandle;
+    }
+
+    /**
+     * Sets the Drawable corresponding to the left handle used
+     * for selecting text. The Drawable defaults to the value of the
+     * textSelectHandleLeft attribute.
+     * Note that any change applied to the handle Drawable will not be visible
+     * until the handle is hidden and then drawn again.
+     *
+     * @see #setTextSelectHandleLeft(int)
+     * @attr ref android.R.styleable#TextView_textSelectHandleLeft
+     */
+    @android.view.RemotableViewMethod
+    public void setTextSelectHandleLeft(@NonNull Drawable textSelectHandleLeft) {
+        Preconditions.checkNotNull(textSelectHandleLeft,
+                "The left text select handle should not be null.");
+        mTextSelectHandleLeft = textSelectHandleLeft;
+        mTextSelectHandleLeftRes = 0;
+        if (mEditor != null) {
+            mEditor.loadHandleDrawables(true /* overwrite */);
+        }
+    }
+
+    /**
+     * Sets the Drawable corresponding to the left handle used
+     * for selecting text. The Drawable defaults to the value of the
+     * textSelectHandleLeft attribute.
+     * Note that any change applied to the handle Drawable will not be visible
+     * until the handle is hidden and then drawn again.
+     *
+     * @see #setTextSelectHandleLeft(Drawable)
+     * @attr ref android.R.styleable#TextView_textSelectHandleLeft
+     */
+    @android.view.RemotableViewMethod
+    public void setTextSelectHandleLeft(@DrawableRes int textSelectHandleLeft) {
+        Preconditions.checkArgumentPositive(textSelectHandleLeft,
+                "The text select left handle should be a valid drawable resource id.");
+        setTextSelectHandleLeft(mContext.getDrawable(textSelectHandleLeft));
+    }
+
+    /**
+     * Returns the Drawable corresponding to the left handle used
+     * for selecting text.
+     * Note that any change applied to the handle Drawable will not be visible
+     * until the handle is hidden and then drawn again.
+     *
+     * @return the left text selection handle drawable
+     *
+     * @see #setTextSelectHandleLeft(Drawable)
+     * @see #setTextSelectHandleLeft(int)
+     * @attr ref android.R.styleable#TextView_textSelectHandleLeft
+     */
+    @Nullable public Drawable getTextSelectHandleLeft() {
+        if (mTextSelectHandleLeft == null && mTextSelectHandleLeftRes != 0) {
+            mTextSelectHandleLeft = mContext.getDrawable(mTextSelectHandleLeftRes);
+        }
+        return mTextSelectHandleLeft;
+    }
+
+    /**
+     * Sets the Drawable corresponding to the right handle used
+     * for selecting text. The Drawable defaults to the value of the
+     * textSelectHandleRight attribute.
+     * Note that any change applied to the handle Drawable will not be visible
+     * until the handle is hidden and then drawn again.
+     *
+     * @see #setTextSelectHandleRight(int)
+     * @attr ref android.R.styleable#TextView_textSelectHandleRight
+     */
+    @android.view.RemotableViewMethod
+    public void setTextSelectHandleRight(@NonNull Drawable textSelectHandleRight) {
+        Preconditions.checkNotNull(textSelectHandleRight,
+                "The right text select handle should not be null.");
+        mTextSelectHandleRight = textSelectHandleRight;
+        mTextSelectHandleRightRes = 0;
+        if (mEditor != null) {
+            mEditor.loadHandleDrawables(true /* overwrite */);
+        }
+    }
+
+    /**
+     * Sets the Drawable corresponding to the right handle used
+     * for selecting text. The Drawable defaults to the value of the
+     * textSelectHandleRight attribute.
+     * Note that any change applied to the handle Drawable will not be visible
+     * until the handle is hidden and then drawn again.
+     *
+     * @see #setTextSelectHandleRight(Drawable)
+     * @attr ref android.R.styleable#TextView_textSelectHandleRight
+     */
+    @android.view.RemotableViewMethod
+    public void setTextSelectHandleRight(@DrawableRes int textSelectHandleRight) {
+        Preconditions.checkArgumentPositive(textSelectHandleRight,
+                "The text select right handle should be a valid drawable resource id.");
+        setTextSelectHandleRight(mContext.getDrawable(textSelectHandleRight));
+    }
+
+    /**
+     * Returns the Drawable corresponding to the right handle used
+     * for selecting text.
+     *
+     * @return the right text selection handle drawable
+     *
+     * @see #setTextSelectHandleRight(Drawable)
+     * @see #setTextSelectHandleRight(int)
+     * @attr ref android.R.styleable#TextView_textSelectHandleRight
+     */
+    @Nullable public Drawable getTextSelectHandleRight() {
+        if (mTextSelectHandleRight == null && mTextSelectHandleRightRes != 0) {
+            mTextSelectHandleRight = mContext.getDrawable(mTextSelectHandleRightRes);
+        }
+        return mTextSelectHandleRight;
+    }
+
+    /**
      * Sets the text appearance from the specified style resource.
      * <p>
      * Use a framework-defined {@code TextAppearance} style like
diff --git a/core/java/com/android/internal/app/AlertController.java b/core/java/com/android/internal/app/AlertController.java
index d7031ea..3462e08 100644
--- a/core/java/com/android/internal/app/AlertController.java
+++ b/core/java/com/android/internal/app/AlertController.java
@@ -191,7 +191,8 @@
 
     public static final AlertController create(Context context, DialogInterface di, Window window) {
         final TypedArray a = context.obtainStyledAttributes(
-                null, R.styleable.AlertDialog, R.attr.alertDialogStyle, 0);
+                null, R.styleable.AlertDialog, R.attr.alertDialogStyle,
+                R.style.Theme_DeviceDefault_Settings);
         int controllerType = a.getInt(R.styleable.AlertDialog_controllerType, 0);
         a.recycle();
 
diff --git a/core/java/com/android/internal/app/IAppOpsService.aidl b/core/java/com/android/internal/app/IAppOpsService.aidl
index 768dddd..049103b 100644
--- a/core/java/com/android/internal/app/IAppOpsService.aidl
+++ b/core/java/com/android/internal/app/IAppOpsService.aidl
@@ -17,6 +17,7 @@
 package com.android.internal.app;
 
 import android.app.AppOpsManager;
+import android.content.pm.ParceledListSlice;
 import android.os.Bundle;
 import com.android.internal.app.IAppOpsCallback;
 import com.android.internal.app.IAppOpsActiveCallback;
@@ -40,6 +41,10 @@
     int checkPackage(int uid, String packageName);
     List<AppOpsManager.PackageOps> getPackagesForOps(in int[] ops);
     List<AppOpsManager.PackageOps> getOpsForPackage(int uid, String packageName, in int[] ops);
+    ParceledListSlice getAllHistoricalPackagesOps(in String[] ops,
+            long beginTimeMillis, long endTimeMillis);
+    AppOpsManager.HistoricalPackageOps getHistoricalPackagesOps(int uid, String packageName,
+            in String[] ops, long beginTimeMillis, long endTimeMillis);
     List<AppOpsManager.PackageOps> getUidOps(int uid, in int[] ops);
     void setUidMode(int code, int uid, int mode);
     void setMode(int code, int uid, String packageName, int mode);
diff --git a/core/java/com/android/server/net/BaseNetdEventCallback.java b/core/java/com/android/server/net/BaseNetdEventCallback.java
index fdba2f3..97247aa 100644
--- a/core/java/com/android/server/net/BaseNetdEventCallback.java
+++ b/core/java/com/android/server/net/BaseNetdEventCallback.java
@@ -26,8 +26,8 @@
  */
 public class BaseNetdEventCallback extends INetdEventCallback.Stub {
     @Override
-    public void onDnsEvent(String hostname, String[] ipAddresses,
-            int ipAddressesCount, long timestamp, int uid) {
+    public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
+            String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
         // default no-op
     }
 
diff --git a/core/jni/android_media_AudioFormat.h b/core/jni/android_media_AudioFormat.h
index f7f13a5..99b5f85 100644
--- a/core/jni/android_media_AudioFormat.h
+++ b/core/jni/android_media_AudioFormat.h
@@ -37,6 +37,7 @@
 #define ENCODING_AAC_XHE        16
 #define ENCODING_AC4            17
 #define ENCODING_E_AC3_JOC      18
+#define ENCODING_DOLBY_MAT      19
 
 #define ENCODING_INVALID    0
 #define ENCODING_DEFAULT    1
@@ -85,6 +86,8 @@
         return AUDIO_FORMAT_E_AC3_JOC;
     case ENCODING_DEFAULT:
         return AUDIO_FORMAT_DEFAULT;
+    case ENCODING_DOLBY_MAT:
+        return AUDIO_FORMAT_MAT;
     default:
         return AUDIO_FORMAT_INVALID;
     }
@@ -134,6 +137,11 @@
         return ENCODING_AC4;
     case AUDIO_FORMAT_E_AC3_JOC:
         return ENCODING_E_AC3_JOC;
+    case AUDIO_FORMAT_MAT:
+    case AUDIO_FORMAT_MAT_1_0:
+    case AUDIO_FORMAT_MAT_2_0:
+    case AUDIO_FORMAT_MAT_2_1:
+        return ENCODING_DOLBY_MAT;
     case AUDIO_FORMAT_DEFAULT:
         return ENCODING_DEFAULT;
     default:
diff --git a/core/jni/android_os_GraphicsEnvironment.cpp b/core/jni/android_os_GraphicsEnvironment.cpp
index e64da5c..80572f3 100644
--- a/core/jni/android_os_GraphicsEnvironment.cpp
+++ b/core/jni/android_os_GraphicsEnvironment.cpp
@@ -58,12 +58,20 @@
     }
 }
 
+void setDebugLayersGLES_native(JNIEnv* env, jobject clazz, jstring layers) {
+    if (layers != nullptr) {
+        ScopedUtfChars layersChars(env, layers);
+        android::GraphicsEnv::getInstance().setDebugLayersGLES(layersChars.c_str());
+    }
+}
+
 const JNINativeMethod g_methods[] = {
     { "getCanLoadSystemLibraries", "()I", reinterpret_cast<void*>(getCanLoadSystemLibraries_native) },
     { "setDriverPath", "(Ljava/lang/String;)V", reinterpret_cast<void*>(setDriverPath) },
     { "setAngleInfo", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZLjava/io/FileDescriptor;JJ)V", reinterpret_cast<void*>(setAngleInfo_native) },
     { "setLayerPaths", "(Ljava/lang/ClassLoader;Ljava/lang/String;)V", reinterpret_cast<void*>(setLayerPaths_native) },
     { "setDebugLayers", "(Ljava/lang/String;)V", reinterpret_cast<void*>(setDebugLayers_native) },
+    { "setDebugLayersGLES", "(Ljava/lang/String;)V", reinterpret_cast<void*>(setDebugLayersGLES_native) },
 };
 
 const char* const kGraphicsEnvironmentName = "android/os/GraphicsEnvironment";
diff --git a/core/jni/android_view_RenderNode.cpp b/core/jni/android_view_RenderNode.cpp
index bb71a5d..e89b593 100644
--- a/core/jni/android_view_RenderNode.cpp
+++ b/core/jni/android_view_RenderNode.cpp
@@ -295,6 +295,22 @@
     return SET_AND_DIRTY(setBottom, bottom, RenderNode::Y);
 }
 
+static jint android_view_RenderNode_getLeft(jlong renderNodePtr) {
+    return reinterpret_cast<RenderNode*>(renderNodePtr)->stagingProperties().getLeft();
+}
+
+static jint android_view_RenderNode_getTop(jlong renderNodePtr) {
+    return reinterpret_cast<RenderNode*>(renderNodePtr)->stagingProperties().getTop();
+}
+
+static jint android_view_RenderNode_getRight(jlong renderNodePtr) {
+    return reinterpret_cast<RenderNode*>(renderNodePtr)->stagingProperties().getRight();
+}
+
+static jint android_view_RenderNode_getBottom(jlong renderNodePtr) {
+    return reinterpret_cast<RenderNode*>(renderNodePtr)->stagingProperties().getBottom();
+}
+
 static jboolean android_view_RenderNode_setLeftTopRightBottom(jlong renderNodePtr,
         int left, int top, int right, int bottom) {
     RenderNode* renderNode = reinterpret_cast<RenderNode*>(renderNodePtr);
@@ -645,6 +661,10 @@
     { "nSetTop",               "(JI)Z",  (void*) android_view_RenderNode_setTop },
     { "nSetRight",             "(JI)Z",  (void*) android_view_RenderNode_setRight },
     { "nSetBottom",            "(JI)Z",  (void*) android_view_RenderNode_setBottom },
+    { "nGetLeft",              "(J)I",  (void*) android_view_RenderNode_getLeft },
+    { "nGetTop",               "(J)I",  (void*) android_view_RenderNode_getTop },
+    { "nGetRight",             "(J)I",  (void*) android_view_RenderNode_getRight },
+    { "nGetBottom",            "(J)I",  (void*) android_view_RenderNode_getBottom },
     { "nSetLeftTopRightBottom","(JIIII)Z", (void*) android_view_RenderNode_setLeftTopRightBottom },
     { "nOffsetLeftAndRight",   "(JI)Z",  (void*) android_view_RenderNode_offsetLeftAndRight },
     { "nOffsetTopAndBottom",   "(JI)Z",  (void*) android_view_RenderNode_offsetTopAndBottom },
diff --git a/core/proto/android/providers/settings/global.proto b/core/proto/android/providers/settings/global.proto
index 47dbc07..3072977 100644
--- a/core/proto/android/providers/settings/global.proto
+++ b/core/proto/android/providers/settings/global.proto
@@ -394,13 +394,16 @@
 
         // App allowed to load GPU debug layers.
         optional SettingProto debug_app = 1;
-        // Ordered GPU debug layer list
+        // Ordered GPU debug layer list for Vulkan
         // i.e. <layer1>:<layer2>:...:<layerN>
         optional SettingProto debug_layers = 2 [ (android.privacy).dest = DEST_AUTOMATIC ];
         // App will load ANGLE instead of native GLES drivers.
         optional SettingProto angle_enabled_app = 3;
         // App that can provide layer libraries.
         optional SettingProto debug_layer_app = 4;
+        // Ordered GPU debug layer list for GLES
+        // i.e. <layer1>:<layer2>:...:<layerN>
+        optional SettingProto debug_layers_gles = 5;
     }
     optional Gpu gpu = 59;
 
diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml
index 48d1dff..093a860 100644
--- a/core/res/AndroidManifest.xml
+++ b/core/res/AndroidManifest.xml
@@ -401,6 +401,7 @@
     <protected-broadcast android:name="android.telecom.action.DEFAULT_DIALER_CHANGED" />
     <protected-broadcast android:name="android.provider.action.DEFAULT_SMS_PACKAGE_CHANGED" />
     <protected-broadcast android:name="android.provider.action.SMS_MMS_DB_CREATED" />
+    <protected-broadcast android:name="android.provider.action.SMS_MMS_DB_LOST" />
     <protected-broadcast android:name="android.intent.action.CONTENT_CHANGED" />
     <protected-broadcast android:name="android.provider.Telephony.MMS_DOWNLOADED" />
 
@@ -3018,6 +3019,14 @@
     <permission android:name="android.permission.BIND_TEXTCLASSIFIER_SERVICE"
                 android:protectionLevel="signature" />
 
+    <!-- Must be required by a android.service.intelligence.IntelligenceService,
+         to ensure that only the system can bind to it.
+         @SystemApi @hide This is not a third-party API (intended for OEMs and system apps).
+         <p>Protection level: signature
+    -->
+    <permission android:name="android.permission.BIND_INTELLIGENCE_SERVICE"
+                android:protectionLevel="signature" />
+
     <!-- Must be required by hotword enrollment application,
          to ensure that only the system can interact with it.
          @hide <p>Not for use by third-party applications.</p> -->
diff --git a/core/res/res/values/strings.xml b/core/res/res/values/strings.xml
index 9ea82a9..8b7cafb 100644
--- a/core/res/res/values/strings.xml
+++ b/core/res/res/values/strings.xml
@@ -1130,14 +1130,13 @@
     <string name="permdesc_accessFineLocation">This app can get your exact location only when it is in the foreground. These location services must be turned on and available on your phone for the app to be able to use them. This may increase battery consumption.</string>
 
     <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
-    <string name="permlab_accessCoarseLocation">access approximate location
-      (network-based)</string>
+    <string name="permlab_accessCoarseLocation">access approximate location (network-based) only in the foreground</string>
     <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
-    <string name="permdesc_accessCoarseLocation" product="tablet">This app can get your location based on network sources such as cell towers and Wi-Fi networks. These location services must be turned on and available on your tablet for the app to be able to use them.</string>
+    <string name="permdesc_accessCoarseLocation" product="tablet">This app can get your location based on network sources such as cell towers and Wi-Fi networks, but only when when the app is in the foreground. These location services must be turned on and available on your tablet for the app to be able to use them.</string>
     <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
-    <string name="permdesc_accessCoarseLocation" product="tv">This app can get your location based on network sources such as cell towers and Wi-Fi networks. These location services must be turned on and available on your TV for the app to be able to use them.</string>
+    <string name="permdesc_accessCoarseLocation" product="tv">This app can get your location based on network sources such as cell towers and Wi-Fi networks, but only when when the app is in the foreground. These location services must be turned on and available on your TV for the app to be able to use them.</string>
     <!-- Description of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
-    <string name="permdesc_accessCoarseLocation" product="default">This app can get your location based on network sources such as cell towers and Wi-Fi networks. These location services must be turned on and available on your phone for the app to be able to use them.</string>
+    <string name="permdesc_accessCoarseLocation" product="default">This app can get your location based on network sources such as cell towers and Wi-Fi networks, but only when the app is in the foreground. These location services must be turned on and available on your phone for the app to be able to use them.</string>
 
     <!-- Title of an application permission, listed so the user can choose whether they want to allow the application to do this. -->
     <string name="permlab_accessBackgroundLocation">access location in the background</string>
diff --git a/core/tests/coretests/src/android/provider/SettingsBackupTest.java b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
index 182f189..c298770 100644
--- a/core/tests/coretests/src/android/provider/SettingsBackupTest.java
+++ b/core/tests/coretests/src/android/provider/SettingsBackupTest.java
@@ -451,6 +451,7 @@
                     Settings.Global.ENABLE_GPU_DEBUG_LAYERS,
                     Settings.Global.GPU_DEBUG_APP,
                     Settings.Global.GPU_DEBUG_LAYERS,
+                    Settings.Global.GPU_DEBUG_LAYERS_GLES,
                     Settings.Global.ANGLE_ENABLED_APP,
                     Settings.Global.GPU_DEBUG_LAYER_APP,
                     Settings.Global.ENABLE_GNSS_RAW_MEAS_FULL_TRACKING,
diff --git a/data/etc/platform.xml b/data/etc/platform.xml
index 499ad38..68f24fb 100644
--- a/data/etc/platform.xml
+++ b/data/etc/platform.xml
@@ -189,12 +189,14 @@
                       targetSdk="16">
         <new-permission name="android.permission.WRITE_CALL_LOG" />
     </split-permission>
+    <!-- STOPSHIP(b/118882117): change targetSdk to Q when SDK version finalised -->
     <split-permission name="android.permission.ACCESS_FINE_LOCATION"
-                      targetSdk="28">
+                      targetSdk="10000">
         <new-permission name="android.permission.ACCESS_BACKGROUND_LOCATION" />
     </split-permission>
+    <!-- STOPSHIP(b/118882117): change targetSdk to Q when SDK version finalised -->
     <split-permission name="android.permission.ACCESS_COARSE_LOCATION"
-                      targetSdk="28">
+                      targetSdk="10000">
         <new-permission name="android.permission.ACCESS_BACKGROUND_LOCATION" />
     </split-permission>
 
diff --git a/graphics/java/android/graphics/Canvas.java b/graphics/java/android/graphics/Canvas.java
index e35a3be..3b0dc9d 100644
--- a/graphics/java/android/graphics/Canvas.java
+++ b/graphics/java/android/graphics/Canvas.java
@@ -205,11 +205,70 @@
         mBitmap = bitmap;
     }
 
-    /** @hide */
-    public void insertReorderBarrier() {}
+    /**
+     * @deprecated use {@link #enableZ()} instead
+     * @hide */
+    @Deprecated
+    public void insertReorderBarrier() {
+        enableZ();
+    }
 
-    /** @hide */
-    public void insertInorderBarrier() {}
+    /**
+     * @deprecated use {@link #disableZ()} instead
+     * @hide */
+    @Deprecated
+    public void insertInorderBarrier() {
+        disableZ();
+    }
+
+    /**
+     * <p>Enables Z support which defaults to disabled. This allows for RenderNodes drawn with
+     * {@link #drawRenderNode(RenderNode)} to be re-arranged based off of their
+     * {@link RenderNode#getElevation()} and {@link RenderNode#getTranslationZ()}
+     * values. It also enables rendering of shadows for RenderNodes with an elevation or
+     * translationZ.</p>
+     *
+     * <p>Any draw reordering will not be moved before this call. A typical usage of this might
+     * look something like:
+     *
+     * <pre class="prettyprint">
+     *     void draw(Canvas canvas) {
+     *         // Draw any background content
+     *         canvas.drawColor(backgroundColor);
+     *
+     *         // Begin drawing that may be reordered based off of Z
+     *         canvas.enableZ();
+     *         for (RenderNode child : children) {
+     *             canvas.drawRenderNode(child);
+     *         }
+     *         // End drawing that may be reordered based off of Z
+     *         canvas.disableZ();
+     *
+     *         // Draw any overlays
+     *         canvas.drawText("I'm on top of everything!", 0, 0, paint);
+     *     }
+     * </pre>
+     * </p>
+     *
+     * Note: This is not impacted by any {@link #save()} or {@link #restore()} calls as it is not
+     * considered to be part of the current matrix or clip.
+     *
+     * See {@link #disableZ()}
+     */
+    public void enableZ() {
+    }
+
+    /**
+     * Disables Z support, preventing any RenderNodes drawn after this point from being
+     * visually reordered or having shadows rendered.
+     *
+     * Note: This is not impacted by any {@link #save()} or {@link #restore()} calls as it is not
+     * considered to be part of the current matrix or clip.
+     *
+     * See {@link #enableZ()}
+     */
+    public void disableZ() {
+    }
 
     /**
      * Return true if the device that the current layer draws into is opaque
@@ -2110,4 +2169,17 @@
         super.drawVertices(mode, vertexCount, verts, vertOffset, texs, texOffset,
                 colors, colorOffset, indices, indexOffset, indexCount, paint);
     }
+
+    /**
+     * Draws the given RenderNode. This is only supported in hardware rendering, which can be
+     * verified by asserting that {@link #isHardwareAccelerated()} is true. If
+     * {@link #isHardwareAccelerated()} is false then this throws an exception.
+     *
+     * See {@link RenderNode} for more information on what a RenderNode is and how to use it.
+     *
+     * @param renderNode The RenderNode to draw, must be non-null.
+     */
+    public void drawRenderNode(@NonNull RenderNode renderNode) {
+        throw new IllegalArgumentException("Software rendering doesn't support drawRenderNode");
+    }
 }
diff --git a/graphics/java/android/graphics/RecordingCanvas.java b/graphics/java/android/graphics/RecordingCanvas.java
index 7af006b..fd5d624 100644
--- a/graphics/java/android/graphics/RecordingCanvas.java
+++ b/graphics/java/android/graphics/RecordingCanvas.java
@@ -18,7 +18,6 @@
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
-import android.annotation.UnsupportedAppUsage;
 import android.util.Pools.SynchronizedPool;
 import android.view.TextureLayer;
 
@@ -27,17 +26,20 @@
 
 /**
  * A Canvas implementation that records view system drawing operations for deferred rendering.
- * This is intended for use with RenderNode. This class keeps a list of all the Paint and
- * Bitmap objects that it draws, preventing the backing memory of Bitmaps from being freed while
+ * This is used in combination with RenderNode. This class keeps a list of all the Paint and
+ * Bitmap objects that it draws, preventing the backing memory of Bitmaps from being released while
  * the RecordingCanvas is still holding a native reference to the memory.
  *
- * @hide
+ * This is obtained by calling {@link RenderNode#startRecording()} and is valid until the matching
+ * {@link RenderNode#endRecording()} is called. It must not be retained beyond that as it is
+ * internally reused.
  */
 public final class RecordingCanvas extends BaseRecordingCanvas {
     // The recording canvas pool should be large enough to handle a deeply nested
     // view hierarchy because display lists are generated recursively.
     private static final int POOL_LIMIT = 25;
 
+    /** @hide */
     public static final int MAX_BITMAP_SIZE = 100 * 1024 * 1024; // 100 MB
 
     private static final SynchronizedPool<RecordingCanvas> sPool =
@@ -50,6 +52,7 @@
     private int mWidth;
     private int mHeight;
 
+    /** @hide */
     static RecordingCanvas obtain(@NonNull RenderNode node, int width, int height) {
         if (node == null) throw new IllegalArgumentException("node cannot be null");
         RecordingCanvas canvas = sPool.acquire();
@@ -65,15 +68,18 @@
         return canvas;
     }
 
+    /** @hide */
     void recycle() {
         mNode = null;
         sPool.release(this);
     }
 
+    /** @hide */
     long finishRecording() {
         return nFinishRecording(mNativeCanvasWrapper);
     }
 
+    /** @hide */
     @Override
     public boolean isRecordingFor(Object o) {
         return o == mNode;
@@ -138,12 +144,12 @@
     ///////////////////////////////////////////////////////////////////////////
 
     @Override
-    public void insertReorderBarrier() {
+    public void enableZ() {
         nInsertReorderBarrier(mNativeCanvasWrapper, true);
     }
 
     @Override
-    public void insertInorderBarrier() {
+    public void disableZ() {
         nInsertReorderBarrier(mNativeCanvasWrapper, false);
     }
 
@@ -159,7 +165,6 @@
      *
      * @hide
      */
-    @UnsupportedAppUsage
     public void callDrawGLFunction2(long drawGLFunction) {
         nCallDrawGLFunction(mNativeCanvasWrapper, drawGLFunction, null);
     }
@@ -178,7 +183,6 @@
      *
      * @hide
      */
-    @UnsupportedAppUsage
     public void drawGLFunctor2(long drawGLFunctor, @Nullable Runnable releasedCallback) {
         nCallDrawGLFunction(mNativeCanvasWrapper, drawGLFunctor, releasedCallback);
     }
@@ -192,8 +196,8 @@
      *
      * @param renderNode The RenderNode to draw.
      */
-    @UnsupportedAppUsage
-    public void drawRenderNode(RenderNode renderNode) {
+    @Override
+    public void drawRenderNode(@NonNull RenderNode renderNode) {
         nDrawRenderNode(mNativeCanvasWrapper, renderNode.mNativeRenderNode);
     }
 
@@ -225,7 +229,6 @@
      *
      * @hide
      */
-    @UnsupportedAppUsage
     public void drawCircle(CanvasProperty<Float> cx, CanvasProperty<Float> cy,
             CanvasProperty<Float> radius, CanvasProperty<Paint> paint) {
         nDrawCircle(mNativeCanvasWrapper, cx.getNativeContainer(), cy.getNativeContainer(),
@@ -254,6 +257,7 @@
                 paint.getNativeContainer());
     }
 
+    /** @hide */
     @Override
     protected void throwIfCannotDraw(Bitmap bitmap) {
         super.throwIfCannotDraw(bitmap);
diff --git a/graphics/java/android/graphics/RenderNode.java b/graphics/java/android/graphics/RenderNode.java
index 320fb20..12128b3 100644
--- a/graphics/java/android/graphics/RenderNode.java
+++ b/graphics/java/android/graphics/RenderNode.java
@@ -21,6 +21,7 @@
 import android.annotation.Nullable;
 import android.view.NativeVectorDrawableAnimator;
 import android.view.RenderNodeAnimator;
+import android.view.Surface;
 import android.view.View;
 
 import dalvik.annotation.optimization.CriticalNative;
@@ -137,7 +138,28 @@
  * that the RenderNode is only used on the same thread it is drawn with. For example when using
  * RenderNode with a custom View, then that RenderNode must only be used from the UI thread.</p>
  *
- * @hide
+ * <h3>When to re-render</h3>
+ * <p>Many of the RenderNode mutation methods, such as {@link #setTranslationX(float)}, return
+ * a boolean indicating if the value actually changed or not. This is useful in detecting
+ * if a new frame should be rendered or not. A typical usage would look like:
+ * <pre class="prettyprint">
+ *     public void translateTo(int x, int y) {
+ *         boolean needsUpdate = myRenderNode.setTranslationX(x);
+ *         needsUpdate |= myRenderNode.setTranslationY(y);
+ *         if (needsUpdate) {
+ *             myOwningView.invalidate();
+ *         }
+ *     }
+ * </pre>
+ * This is marginally faster than doing a more explicit up-front check if the value changed by
+ * comparing the desired value against {@link #getTranslationX()} as it minimizes JNI transitions.
+ * The actual mechanism of requesting a new frame to be rendered will depend on how this
+ * RenderNode is being drawn. If it's drawn to a containing View, as in the above snippet,
+ * then simply invalidating that View works. If instead the RenderNode is being drawn to a Canvas
+ * directly such as with {@link Surface#lockHardwareCanvas()} then a new frame needs to be drawn
+ * by calling {@link Surface#lockHardwareCanvas()}, re-drawing the root RenderNode or whatever
+ * top-level content is desired, and finally calling {@link Surface#unlockCanvasAndPost(Canvas)}.
+ * </p>
  */
 public class RenderNode {
 
@@ -147,7 +169,9 @@
                 RenderNode.class.getClassLoader(), nGetNativeFinalizer(), 1024);
     }
 
-    /** Not for general use; use only if you are ThreadedRenderer or RecordingCanvas.
+    /**
+     * Not for general use; use only if you are ThreadedRenderer or RecordingCanvas.
+     *
      * @hide
      */
     public final long mNativeRenderNode;
@@ -174,9 +198,13 @@
      * drawing operations, and store / apply render properties when drawn.
      *
      * @param name The name of the RenderNode, used for debugging purpose. May be null.
-     *
      * @return A new RenderNode.
      */
+    public static @NonNull RenderNode create(@Nullable String name) {
+        return new RenderNode(name, null);
+    }
+
+    /** @hide */
     public static RenderNode create(String name, @Nullable AnimationHost animationHost) {
         return new RenderNode(name, animationHost);
     }
@@ -186,6 +214,8 @@
      *
      * Note: This will *NOT* incRef() on the native object, however it will
      * decRef() when it is destroyed. The caller should have already incRef'd it
+     *
+     * @hide
      */
     public static RenderNode adopt(long nativePtr) {
         return new RenderNode(nativePtr);
@@ -220,6 +250,8 @@
 
     /**
      * Enable callbacks for position changes.
+     *
+     * @hide
      */
     public void requestPositionUpdates(PositionUpdateListener listener) {
         nRequestPositionUpdates(mNativeRenderNode, listener);
@@ -234,15 +266,13 @@
      * {@link #endRecording()} must be called when the recording is finished in order to apply
      * the updated display list.
      *
-     * @param width The width of the recording viewport. This will not alter the width of the
-     *              RenderNode itself, that must be set with {@link #setLeft(int)} and
-     *              {@link #setRight(int)}
+     * @param width  The width of the recording viewport. This will not alter the width of the
+     *               RenderNode itself, that must be set with {@link #setLeft(int)} and
+     *               {@link #setRight(int)}
      * @param height The height of the recording viewport. This will not alter the height of the
      *               RenderNode itself, that must be set with {@link #setTop(int)} and
      *               {@link #setBottom(int)}.
-     *
      * @return A canvas to record drawing operations.
-     *
      * @see #endRecording()
      * @see #hasDisplayList()
      */
@@ -261,20 +291,20 @@
      * with {@link #setLeftTopRightBottom(int, int, int, int)}.
      */
     public RecordingCanvas startRecording() {
-        return RecordingCanvas.obtain(this,
-                nGetWidth(mNativeRenderNode), nGetHeight(mNativeRenderNode));
+        return startRecording(nGetWidth(mNativeRenderNode), nGetHeight(mNativeRenderNode));
     }
 
     /**
-     * @deprecated use {@link #startRecording(int, int)} instead
      * @hide
+     * @deprecated use {@link #startRecording(int, int)} instead
      */
     @Deprecated
     public RecordingCanvas start(int width, int height) {
         return startRecording(width, height);
     }
 
-    /**`
+    /**
+     * `
      * Ends the recording for this display list. Calling this method marks
      * the display list valid and {@link #hasDisplayList()} will return true.
      *
@@ -294,8 +324,8 @@
     }
 
     /**
-     * @deprecated use {@link #endRecording()} instead
      * @hide
+     * @deprecated use {@link #endRecording()} instead
      */
     @Deprecated
     public void end(RecordingCanvas canvas) {
@@ -373,21 +403,52 @@
     ///////////////////////////////////////////////////////////////////////////
 
     /**
-     * TODO
+     * @hide
+     * @deprecated use {@link #setUseCompositingLayer(boolean, Paint)} instead
      */
+    @Deprecated
     public boolean setLayerType(int layerType) {
         return nSetLayerType(mNativeRenderNode, layerType);
     }
 
     /**
-     * TODO
+     * @hide
+     * @deprecated use {@link #setUseCompositingLayer(boolean, Paint)} instead
      */
+    @Deprecated
     public boolean setLayerPaint(@Nullable Paint paint) {
         return nSetLayerPaint(mNativeRenderNode, paint != null ? paint.getNativeInstance() : 0);
     }
 
     /**
+     * Controls whether or not to force this RenderNode to render to an intermediate buffer.
+     * Internally RenderNode will already promote itself to a composition layer if it's useful
+     * for performance or required for the current combination of {@link #setAlpha(float)} and
+     * {@link #setHasOverlappingRendering(boolean)}.
+     *
+     * The usage of this is instead to allow for either overriding of the internal behavior
+     * if it's measured to be necessary for the particular rendering content in question or, more
+     * usefully, to add a composition effect to the RenderNode via the optional paint parameter.
+     *
+     * Note: When a RenderNode is using a compositing layer it will also result in
+     * clipToBounds=true behavior.
+     *
+     * @param forceToLayer if true this forces the RenderNode to use an intermediate buffer.
+     *                     Default & generally recommended value is false.
+     * @param paint        The blend mode, alpha, and ColorFilter to apply to the compositing layer.
+     *                     Only applies if forceToLayer is true.
+     * @return true if anything changed, false otherwise
+     */
+    public boolean setUseCompositingLayer(boolean forceToLayer, @Nullable Paint paint) {
+        boolean didChange = nSetLayerType(mNativeRenderNode, forceToLayer ? 2 : 0);
+        didChange |= nSetLayerPaint(mNativeRenderNode,
+                paint != null ? paint.getNativeInstance() : 0);
+        return didChange;
+    }
+
+    /**
      * Sets the clip bounds of the RenderNode.
+     *
      * @param rect the bounds to clip to. If null, the clip bounds are reset
      * @return True if the clip bounds changed, false otherwise
      */
@@ -410,19 +471,19 @@
     }
 
     /**
-     * Sets whether the display list should be drawn immediately after the
-     * closest ancestor display list containing a projection receiver.
+     * Sets whether the RenderNode should be drawn immediately after the
+     * closest ancestor RenderNode containing a projection receiver.
      *
      * @param shouldProject true if the display list should be projected onto a
-     *            containing volume.
+     *                      containing volume.
      */
     public boolean setProjectBackwards(boolean shouldProject) {
         return nSetProjectBackwards(mNativeRenderNode, shouldProject);
     }
 
     /**
-     * Sets whether the display list is a projection receiver - that its parent
-     * DisplayList should draw any descendent DisplayLists with
+     * Sets whether the RenderNode is a projection receiver - that its parent
+     * RenderNode should draw any descendent RenderNodes with
      * ProjectBackwards=true directly on top of it. Default value is false.
      */
     public boolean setProjectionReceiver(boolean shouldRecieve) {
@@ -433,14 +494,18 @@
      * Sets the outline, defining the shape that casts a shadow, and the path to
      * be clipped if setClipToOutline is set.
      *
-     * Deep copies the data into native to simplify reference ownership.
+     * This will make a copy of the provided {@link Outline}, so any future modifications
+     * to the outline will need to call {@link #setOutline(Outline)} with the modified
+     * outline for those changes to be applied.
+     *
+     * @param outline The outline to use for this RenderNode.
      */
     public boolean setOutline(@Nullable Outline outline) {
         if (outline == null) {
             return nSetOutlineNone(mNativeRenderNode);
         }
 
-        switch(outline.mMode) {
+        switch (outline.mMode) {
             case Outline.MODE_EMPTY:
                 return nSetOutlineEmpty(mNativeRenderNode);
             case Outline.MODE_ROUND_RECT:
@@ -457,28 +522,63 @@
     }
 
     /**
+     * Checks if the RenderNode has a shadow. That is, if the combination of {@link #getElevation()}
+     * and {@link #getTranslationZ()} is greater than zero, there is an {@link Outline} set with
+     * a valid shadow caster path, and the provided outline has a non-zero
+     * {@link Outline#getAlpha()}.
+     *
      * @return True if this RenderNode has a shadow, false otherwise
      */
     public boolean hasShadow() {
         return nHasShadow(mNativeRenderNode);
     }
 
-    /** setSpotShadowColor */
+    /**
+     * Sets the color of the spot shadow that is drawn when the RenderNode has a positive Z or
+     * elevation value and is drawn inside of a {@link Canvas#enableZ()} section.
+     * <p>
+     * By default the shadow color is black. Generally, this color will be opaque so the intensity
+     * of the shadow is consistent between different RenderNodes with different colors.
+     * <p>
+     * The opacity of the final spot shadow is a function of the shadow caster height, the
+     * alpha channel of the outlineSpotShadowColor (typically opaque), and the
+     * {@link android.R.attr#spotShadowAlpha} theme attribute
+     *
+     * @param color The color this RenderNode will cast for its elevation spot shadow.
+     */
     public boolean setSpotShadowColor(int color) {
         return nSetSpotShadowColor(mNativeRenderNode, color);
     }
 
-    /** setAmbientShadowColor */
-    public boolean setAmbientShadowColor(int color) {
-        return nSetAmbientShadowColor(mNativeRenderNode, color);
-    }
-
-    /** getSpotShadowColor */
+    /**
+     * @return The shadow color set by {@link #setSpotShadowColor(int)}, or black if nothing
+     * was set
+     */
     public int getSpotShadowColor() {
         return nGetSpotShadowColor(mNativeRenderNode);
     }
 
-    /** getAmbientShadowColor */
+    /**
+     * Sets the color of the ambient shadow that is drawn when the RenderNode has a positive Z or
+     * elevation value and is drawn inside of a {@link Canvas#enableZ()} section.
+     * <p>
+     * By default the shadow color is black. Generally, this color will be opaque so the intensity
+     * of the shadow is consistent between different RenderNodes with different colors.
+     * <p>
+     * The opacity of the final ambient shadow is a function of the shadow caster height, the
+     * alpha channel of the outlineAmbientShadowColor (typically opaque), and the
+     * {@link android.R.attr#ambientShadowAlpha} theme attribute.
+     *
+     * @param color The color this RenderNode will cast for its elevation shadow.
+     */
+    public boolean setAmbientShadowColor(int color) {
+        return nSetAmbientShadowColor(mNativeRenderNode, color);
+    }
+
+    /**
+     * @return The shadow color set by {@link #setAmbientShadowColor(int)}, or black if
+     * nothing was set
+     */
     public int getAmbientShadowColor() {
         return nGetAmbientShadowColor(mNativeRenderNode);
     }
@@ -503,6 +603,8 @@
 
     /**
      * Controls the RenderNode's circular reveal clip.
+     *
+     * @hide
      */
     public boolean setRevealClip(boolean shouldClip,
             float x, float y, float radius) {
@@ -514,6 +616,7 @@
      * transforms (such as {@link #setScaleX(float)}, {@link #setRotation(float)}, etc.)
      *
      * @param matrix A transform matrix to apply to this display list
+     * @hide TODO Do we want this?
      */
     public boolean setStaticMatrix(Matrix matrix) {
         return nSetStaticMatrix(mNativeRenderNode, matrix.native_instance);
@@ -526,6 +629,7 @@
      * for the matrix parameter.
      *
      * @param matrix The matrix, null indicates that the matrix should be cleared.
+     * @hide TODO Do we want this?
      */
     public boolean setAnimationMatrix(Matrix matrix) {
         return nSetAnimationMatrix(mNativeRenderNode,
@@ -536,7 +640,6 @@
      * Sets the translucency level for the display list.
      *
      * @param alpha The translucency of the display list, must be a value between 0.0f and 1.0f
-     *
      * @see View#setAlpha(float)
      * @see #getAlpha()
      */
@@ -548,7 +651,6 @@
      * Returns the translucency level of this display list.
      *
      * @return A value between 0.0f and 1.0f
-     *
      * @see #setAlpha(float)
      */
     public float getAlpha() {
@@ -562,7 +664,6 @@
      *
      * @param hasOverlappingRendering False if the content is guaranteed to be non-overlapping,
      *                                true otherwise.
-     *
      * @see android.view.View#hasOverlappingRendering()
      * @see #hasOverlappingRendering()
      */
@@ -573,17 +674,28 @@
     /** @hide */
     @IntDef({USAGE_BACKGROUND})
     @Retention(RetentionPolicy.SOURCE)
-    public @interface UsageHint {}
+    public @interface UsageHint {
+    }
 
-    /** The default usage hint */
+    /**
+     * The default usage hint
+     *
+     * @hide
+     */
     public static final int USAGE_UNKNOWN = 0;
 
-    /** Usage is background content */
+    /**
+     * Usage is background content
+     *
+     * @hide
+     */
     public static final int USAGE_BACKGROUND = 1;
 
     /**
      * Provides a hint on what this RenderNode's display list content contains. This hint is used
      * for automatic content transforms to improve accessibility or similar.
+     *
+     * @hide
      */
     public void setUsageHint(@UsageHint int usageHint) {
         nSetUsageHint(mNativeRenderNode, usageHint);
@@ -593,7 +705,6 @@
      * Indicates whether the content of this display list overlaps.
      *
      * @return True if this display list renders content which overlaps, false otherwise.
-     *
      * @see #setHasOverlappingRendering(boolean)
      */
     public boolean hasOverlappingRendering() {
@@ -623,7 +734,6 @@
      * Sets the translation value for the display list on the X axis.
      *
      * @param translationX The X axis translation value of the display list, in pixels
-     *
      * @see View#setTranslationX(float)
      * @see #getTranslationX()
      */
@@ -644,7 +754,6 @@
      * Sets the translation value for the display list on the Y axis.
      *
      * @param translationY The Y axis translation value of the display list, in pixels
-     *
      * @see View#setTranslationY(float)
      * @see #getTranslationY()
      */
@@ -684,7 +793,6 @@
      * Sets the rotation value for the display list around the Z axis.
      *
      * @param rotation The rotation value of the display list, in degrees
-     *
      * @see View#setRotation(float)
      * @see #getRotation()
      */
@@ -705,7 +813,6 @@
      * Sets the rotation value for the display list around the X axis.
      *
      * @param rotationX The rotation value of the display list, in degrees
-     *
      * @see View#setRotationX(float)
      * @see #getRotationX()
      */
@@ -726,7 +833,6 @@
      * Sets the rotation value for the display list around the Y axis.
      *
      * @param rotationY The rotation value of the display list, in degrees
-     *
      * @see View#setRotationY(float)
      * @see #getRotationY()
      */
@@ -747,7 +853,6 @@
      * Sets the scale value for the display list on the X axis.
      *
      * @param scaleX The scale value of the display list
-     *
      * @see View#setScaleX(float)
      * @see #getScaleX()
      */
@@ -768,7 +873,6 @@
      * Sets the scale value for the display list on the Y axis.
      *
      * @param scaleY The scale value of the display list
-     *
      * @see View#setScaleY(float)
      * @see #getScaleY()
      */
@@ -789,7 +893,6 @@
      * Sets the pivot value for the display list on the X axis
      *
      * @param pivotX The pivot value of the display list on the X axis, in pixels
-     *
      * @see View#setPivotX(float)
      * @see #getPivotX()
      */
@@ -810,7 +913,6 @@
      * Sets the pivot value for the display list on the Y axis
      *
      * @param pivotY The pivot value of the display list on the Y axis, in pixels
-     *
      * @see View#setPivotY(float)
      * @see #getPivotY()
      */
@@ -827,135 +929,222 @@
         return nGetPivotY(mNativeRenderNode);
     }
 
+    /**
+     * @return Whether or not a pivot was explicitly set with {@link #setPivotX(float)} or
+     * {@link #setPivotY(float)}. If no pivot has been set then the pivot will be the center
+     * of the RenderNode.
+     */
     public boolean isPivotExplicitlySet() {
         return nIsPivotExplicitlySet(mNativeRenderNode);
     }
 
-    /** lint */
+    /**
+     * Clears any pivot previously set by a call to  {@link #setPivotX(float)} or
+     * {@link #setPivotY(float)}. After calling this {@link #isPivotExplicitlySet()} will be false
+     * and the pivot used for rotation will return to default of being centered on the view.
+     */
     public boolean resetPivot() {
         return nResetPivot(mNativeRenderNode);
     }
 
     /**
-     * Sets the camera distance for the display list. Refer to
-     * {@link View#setCameraDistance(float)} for more information on how to
-     * use this property.
+     * <p>Sets the distance along the Z axis (orthogonal to the X/Y plane on which
+     * RenderNodes are drawn) from the camera to this RenderNode. The camera's distance
+     * affects 3D transformations, for instance rotations around the X and Y
+     * axis. If the rotationX or rotationY properties are changed and this view is
+     * large (more than half the size of the screen), it is recommended to always
+     * use a camera distance that's greater than the height (X axis rotation) or
+     * the width (Y axis rotation) of this view.</p>
      *
-     * @param distance The distance in Z of the camera of the display list
+     * <p>The distance of the camera from the drawing plane can have an affect on the
+     * perspective distortion of the RenderNode when it is rotated around the x or y axis.
+     * For example, a large distance will result in a large viewing angle, and there
+     * will not be much perspective distortion of the view as it rotates. A short
+     * distance may cause much more perspective distortion upon rotation, and can
+     * also result in some drawing artifacts if the rotated view ends up partially
+     * behind the camera (which is why the recommendation is to use a distance at
+     * least as far as the size of the view, if the view is to be rotated.)</p>
      *
-     * @see View#setCameraDistance(float)
-     * @see #getCameraDistance()
+     * <p>The distance is expressed in pixels and must always be positive</p>
+     *
+     * @param distance The distance in pixels, must always be positive
+     * @see #setRotationX(float)
+     * @see #setRotationY(float)
      */
     public boolean setCameraDistance(float distance) {
-        return nSetCameraDistance(mNativeRenderNode, distance);
+        if (!Float.isFinite(distance) || distance < 0.0f) {
+            throw new IllegalArgumentException("distance must be finite & positive, given="
+                    + distance);
+        }
+        // Native actually wants this to be negative not positive, so we flip it.
+        return nSetCameraDistance(mNativeRenderNode, -distance);
     }
 
     /**
-     * Returns the distance in Z of the camera of the display list.
+     * Returns the distance in Z of the camera for this RenderNode
      *
+     * @return the distance along the Z axis in pixels.
      * @see #setCameraDistance(float)
      */
     public float getCameraDistance() {
-        return nGetCameraDistance(mNativeRenderNode);
+        return -nGetCameraDistance(mNativeRenderNode);
     }
 
     /**
-     * Sets the left position for the display list.
+     * Sets the left position for the RenderNode.
      *
-     * @param left The left position, in pixels, of the display list
-     *
-     * @see View#setLeft(int)
+     * @param left The left position, in pixels, of the RenderNode
+     * @return true if the value changed, false otherwise
      */
     public boolean setLeft(int left) {
         return nSetLeft(mNativeRenderNode, left);
     }
 
     /**
-     * Sets the top position for the display list.
+     * Sets the top position for the RenderNode.
      *
-     * @param top The top position, in pixels, of the display list
-     *
-     * @see View#setTop(int)
+     * @param top The top position, in pixels, of the RenderNode
+     * @return true if the value changed, false otherwise.
      */
     public boolean setTop(int top) {
         return nSetTop(mNativeRenderNode, top);
     }
 
     /**
-     * Sets the right position for the display list.
+     * Sets the right position for the RenderNode.
      *
-     * @param right The right position, in pixels, of the display list
-     *
-     * @see View#setRight(int)
+     * @param right The right position, in pixels, of the RenderNode
+     * @return true if the value changed, false otherwise.
      */
     public boolean setRight(int right) {
         return nSetRight(mNativeRenderNode, right);
     }
 
     /**
-     * Sets the bottom position for the display list.
+     * Sets the bottom position for the RenderNode.
      *
-     * @param bottom The bottom position, in pixels, of the display list
-     *
-     * @see View#setBottom(int)
+     * @param bottom The bottom position, in pixels, of the RenderNode
+     * @return true if the value changed, false otherwise.
      */
     public boolean setBottom(int bottom) {
         return nSetBottom(mNativeRenderNode, bottom);
     }
 
     /**
-     * Sets the left and top positions for the display list
+     * Gets the left position for the RenderNode.
      *
-     * @param left The left position of the display list, in pixels
-     * @param top The top position of the display list, in pixels
-     * @param right The right position of the display list, in pixels
-     * @param bottom The bottom position of the display list, in pixels
+     * See {@link #setLeft(int)}
      *
-     * @see View#setLeft(int)
-     * @see View#setTop(int)
-     * @see View#setRight(int)
-     * @see View#setBottom(int)
+     * @return the left position in pixels
+     */
+    public int getLeft() {
+        return nGetLeft(mNativeRenderNode);
+    }
+
+    /**
+     * Gets the top position for the RenderNode.
+     *
+     * See {@link #setTop(int)}
+     *
+     * @return the top position in pixels
+     */
+    public int getTop() {
+        return nGetTop(mNativeRenderNode);
+    }
+
+    /**
+     * Gets the right position for the RenderNode.
+     *
+     * See {@link #setRight(int)}
+     *
+     * @return the right position in pixels
+     */
+    public int getRight() {
+        return nGetRight(mNativeRenderNode);
+    }
+
+    /**
+     * Gets the bottom position for the RenderNode.
+     *
+     * See {@link #setBottom(int)}
+     *
+     * @return the bottom position in pixels
+     */
+    public int getBottom() {
+        return nGetBottom(mNativeRenderNode);
+    }
+
+    /**
+     * Gets the width of the RenderNode, which is the right - left.
+     *
+     * @return the width of the RenderNode
+     */
+    public int getWidth() {
+        return nGetWidth(mNativeRenderNode);
+    }
+
+    /**
+     * Gets the height of the RenderNode, which is the bottom - top.
+     *
+     * @return the height of the RenderNode
+     */
+    public int getHeight() {
+        return nGetHeight(mNativeRenderNode);
+    }
+
+    /**
+     * Sets the left, top, right, and bottom of the RenderNode.
+     *
+     * @param left   The left position of the RenderNode, in pixels
+     * @param top    The top position of the RenderNode, in pixels
+     * @param right  The right position of the RenderNode, in pixels
+     * @param bottom The bottom position of the RenderNode, in pixels
+     * @return true if any values changed, false otherwise.
+     * @see #setLeft(int)
+     * @see #setTop(int)
+     * @see #setRight(int)
+     * @see #setBottom(int)
      */
     public boolean setLeftTopRightBottom(int left, int top, int right, int bottom) {
         return nSetLeftTopRightBottom(mNativeRenderNode, left, top, right, bottom);
     }
 
     /**
-     * Offsets the left and right positions for the display list
+     * Offsets the left and right positions for the RenderNode
      *
-     * @param offset The amount that the left and right positions of the display
-     *               list are offset, in pixels
-     *
-     * @see View#offsetLeftAndRight(int)
+     * @param offset The amount that the left and right positions are offset in pixels
+     * @return true if any values changed, false otherwise.
      */
     public boolean offsetLeftAndRight(int offset) {
         return nOffsetLeftAndRight(mNativeRenderNode, offset);
     }
 
     /**
-     * Offsets the top and bottom values for the display list
+     * Offsets the top and bottom values for the RenderNode
      *
-     * @param offset The amount that the top and bottom positions of the display
-     *               list are offset, in pixels
-     *
-     * @see View#offsetTopAndBottom(int)
+     * @param offset The amount that the left and right positions are offset in pixels
+     * @return true if any values changed, false otherwise.
      */
     public boolean offsetTopAndBottom(int offset) {
         return nOffsetTopAndBottom(mNativeRenderNode, offset);
     }
 
     /**
-     * Outputs the display list to the log. This method exists for use by
+     * Outputs the RenderNode to the log. This method exists for use by
      * tools to output display lists for selected nodes to the log.
+     *
+     * @hide TODO: Expose? Should the shape of this be different than forced dump to logcat?
      */
     public void output() {
         nOutput(mNativeRenderNode);
     }
 
     /**
-     * Gets the size of the DisplayList for debug purposes.
+     * Gets the approximate memory usage of the RenderNode for debug purposes. Does not include
+     * the memory usage of any child RenderNodes nor any bitmaps, only the memory usage of
+     * this RenderNode and any data it owns.
      */
-    public int getDebugSize() {
+    public int computeApproximateMemoryUsage() {
         return nGetDebugSize(mNativeRenderNode);
     }
 
@@ -995,13 +1184,16 @@
      * For now this interface exists to de-couple RenderNode from anything View-specific in a
      * bit of a kludge.
      *
-     * @hide */
+     * @hide
+     */
     public interface AnimationHost {
-        /** checkstyle */
+        /** @hide */
         void registerAnimatingRenderNode(RenderNode animator);
-        /** checkstyle */
+
+        /** @hide */
         void registerVectorDrawableAnimator(NativeVectorDrawableAnimator animator);
-        /** checkstyle */
+
+        /** @hide */
         boolean isAttached();
     }
 
@@ -1039,14 +1231,18 @@
     private static native long nCreate(String name);
 
     private static native long nGetNativeFinalizer();
+
     private static native void nOutput(long renderNode);
+
     private static native int nGetDebugSize(long renderNode);
+
     private static native void nRequestPositionUpdates(long renderNode,
             PositionUpdateListener callback);
 
     // Animations
 
     private static native void nAddAnimator(long renderNode, long animatorPtr);
+
     private static native void nEndAllAnimators(long renderNode);
 
 
@@ -1069,8 +1265,10 @@
 
     @CriticalNative
     private static native void nGetTransformMatrix(long renderNode, long nativeMatrix);
+
     @CriticalNative
     private static native void nGetInverseTransformMatrix(long renderNode, long nativeMatrix);
+
     @CriticalNative
     private static native boolean nHasIdentityMatrix(long renderNode);
 
@@ -1078,135 +1276,208 @@
 
     @CriticalNative
     private static native boolean nOffsetTopAndBottom(long renderNode, int offset);
+
     @CriticalNative
     private static native boolean nOffsetLeftAndRight(long renderNode, int offset);
+
     @CriticalNative
     private static native boolean nSetLeftTopRightBottom(long renderNode, int left, int top,
             int right, int bottom);
-    @CriticalNative
-    private static native boolean nSetBottom(long renderNode, int bottom);
-    @CriticalNative
-    private static native boolean nSetRight(long renderNode, int right);
-    @CriticalNative
-    private static native boolean nSetTop(long renderNode, int top);
+
     @CriticalNative
     private static native boolean nSetLeft(long renderNode, int left);
+
+    @CriticalNative
+    private static native boolean nSetTop(long renderNode, int top);
+
+    @CriticalNative
+    private static native boolean nSetRight(long renderNode, int right);
+
+    @CriticalNative
+    private static native boolean nSetBottom(long renderNode, int bottom);
+
+    @CriticalNative
+    private static native int nGetLeft(long renderNode);
+
+    @CriticalNative
+    private static native int nGetTop(long renderNode);
+
+    @CriticalNative
+    private static native int nGetRight(long renderNode);
+
+    @CriticalNative
+    private static native int nGetBottom(long renderNode);
+
     @CriticalNative
     private static native boolean nSetCameraDistance(long renderNode, float distance);
+
     @CriticalNative
     private static native boolean nSetPivotY(long renderNode, float pivotY);
+
     @CriticalNative
     private static native boolean nSetPivotX(long renderNode, float pivotX);
+
     @CriticalNative
     private static native boolean nResetPivot(long renderNode);
+
     @CriticalNative
     private static native boolean nSetLayerType(long renderNode, int layerType);
+
     @CriticalNative
     private static native boolean nSetLayerPaint(long renderNode, long paint);
+
     @CriticalNative
     private static native boolean nSetClipToBounds(long renderNode, boolean clipToBounds);
+
     @CriticalNative
     private static native boolean nSetClipBounds(long renderNode, int left, int top,
             int right, int bottom);
+
     @CriticalNative
     private static native boolean nSetClipBoundsEmpty(long renderNode);
+
     @CriticalNative
     private static native boolean nSetProjectBackwards(long renderNode, boolean shouldProject);
+
     @CriticalNative
     private static native boolean nSetProjectionReceiver(long renderNode, boolean shouldRecieve);
+
     @CriticalNative
     private static native boolean nSetOutlineRoundRect(long renderNode, int left, int top,
             int right, int bottom, float radius, float alpha);
+
     @CriticalNative
     private static native boolean nSetOutlineConvexPath(long renderNode, long nativePath,
             float alpha);
+
     @CriticalNative
     private static native boolean nSetOutlineEmpty(long renderNode);
+
     @CriticalNative
     private static native boolean nSetOutlineNone(long renderNode);
+
     @CriticalNative
     private static native boolean nHasShadow(long renderNode);
+
     @CriticalNative
     private static native boolean nSetSpotShadowColor(long renderNode, int color);
+
     @CriticalNative
     private static native boolean nSetAmbientShadowColor(long renderNode, int color);
+
     @CriticalNative
     private static native int nGetSpotShadowColor(long renderNode);
+
     @CriticalNative
     private static native int nGetAmbientShadowColor(long renderNode);
+
     @CriticalNative
     private static native boolean nSetClipToOutline(long renderNode, boolean clipToOutline);
+
     @CriticalNative
     private static native boolean nSetRevealClip(long renderNode,
             boolean shouldClip, float x, float y, float radius);
+
     @CriticalNative
     private static native boolean nSetAlpha(long renderNode, float alpha);
+
     @CriticalNative
     private static native boolean nSetHasOverlappingRendering(long renderNode,
             boolean hasOverlappingRendering);
+
     @CriticalNative
     private static native void nSetUsageHint(long renderNode, int usageHint);
+
     @CriticalNative
     private static native boolean nSetElevation(long renderNode, float lift);
+
     @CriticalNative
     private static native boolean nSetTranslationX(long renderNode, float translationX);
+
     @CriticalNative
     private static native boolean nSetTranslationY(long renderNode, float translationY);
+
     @CriticalNative
     private static native boolean nSetTranslationZ(long renderNode, float translationZ);
+
     @CriticalNative
     private static native boolean nSetRotation(long renderNode, float rotation);
+
     @CriticalNative
     private static native boolean nSetRotationX(long renderNode, float rotationX);
+
     @CriticalNative
     private static native boolean nSetRotationY(long renderNode, float rotationY);
+
     @CriticalNative
     private static native boolean nSetScaleX(long renderNode, float scaleX);
+
     @CriticalNative
     private static native boolean nSetScaleY(long renderNode, float scaleY);
+
     @CriticalNative
     private static native boolean nSetStaticMatrix(long renderNode, long nativeMatrix);
+
     @CriticalNative
     private static native boolean nSetAnimationMatrix(long renderNode, long animationMatrix);
 
     @CriticalNative
     private static native boolean nHasOverlappingRendering(long renderNode);
+
     @CriticalNative
     private static native boolean nGetClipToOutline(long renderNode);
+
     @CriticalNative
     private static native float nGetAlpha(long renderNode);
+
     @CriticalNative
     private static native float nGetCameraDistance(long renderNode);
+
     @CriticalNative
     private static native float nGetScaleX(long renderNode);
+
     @CriticalNative
     private static native float nGetScaleY(long renderNode);
+
     @CriticalNative
     private static native float nGetElevation(long renderNode);
+
     @CriticalNative
     private static native float nGetTranslationX(long renderNode);
+
     @CriticalNative
     private static native float nGetTranslationY(long renderNode);
+
     @CriticalNative
     private static native float nGetTranslationZ(long renderNode);
+
     @CriticalNative
     private static native float nGetRotation(long renderNode);
+
     @CriticalNative
     private static native float nGetRotationX(long renderNode);
+
     @CriticalNative
     private static native float nGetRotationY(long renderNode);
+
     @CriticalNative
     private static native boolean nIsPivotExplicitlySet(long renderNode);
+
     @CriticalNative
     private static native float nGetPivotX(long renderNode);
+
     @CriticalNative
     private static native float nGetPivotY(long renderNode);
+
     @CriticalNative
     private static native int nGetWidth(long renderNode);
+
     @CriticalNative
     private static native int nGetHeight(long renderNode);
+
     @CriticalNative
     private static native boolean nSetAllowForceDark(long renderNode, boolean allowForceDark);
+
     @CriticalNative
     private static native boolean nGetAllowForceDark(long renderNode);
 }
diff --git a/graphics/java/android/graphics/Typeface.java b/graphics/java/android/graphics/Typeface.java
index 5c0c38e..a09b063 100644
--- a/graphics/java/android/graphics/Typeface.java
+++ b/graphics/java/android/graphics/Typeface.java
@@ -27,10 +27,11 @@
 import android.annotation.Nullable;
 import android.annotation.UnsupportedAppUsage;
 import android.content.res.AssetManager;
+import android.graphics.fonts.Font;
+import android.graphics.fonts.FontFamily;
 import android.graphics.fonts.FontStyle;
 import android.graphics.fonts.FontVariationAxis;
 import android.graphics.fonts.SystemFonts;
-import android.net.Uri;
 import android.os.Build;
 import android.provider.FontRequest;
 import android.provider.FontsContract;
@@ -50,13 +51,10 @@
 
 import java.io.File;
 import java.io.FileDescriptor;
-import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -126,7 +124,8 @@
 
     // We cannot support sSystemFallbackMap since we will migrate to public FontFamily API.
     @UnsupportedAppUsage
-    static final Map<String, FontFamily[]> sSystemFallbackMap = Collections.emptyMap();
+    static final Map<String, android.graphics.FontFamily[]> sSystemFallbackMap =
+            Collections.emptyMap();
 
     /**
      * @hide
@@ -164,6 +163,9 @@
     private int[] mSupportedAxes;
     private static final int[] EMPTY_AXES = {};
 
+    // The underlying font families.
+    private final FontFamily[] mFamilies;
+
     @UnsupportedAppUsage
     private static void setDefault(Typeface t) {
         sDefaultTypeface = t;
@@ -192,38 +194,6 @@
 
     /**
      * @hide
-     * Used by Resources to load a font resource of type font file.
-     */
-    @Nullable
-    public static Typeface createFromResources(AssetManager mgr, String path, int cookie) {
-        synchronized (sDynamicCacheLock) {
-            final String key = Builder.createAssetUid(
-                    mgr, path, 0 /* ttcIndex */, null /* axes */,
-                    RESOLVE_BY_FONT_TABLE /* weight */, RESOLVE_BY_FONT_TABLE /* italic */,
-                    DEFAULT_FAMILY);
-            Typeface typeface = sDynamicTypefaceCache.get(key);
-            if (typeface != null) return typeface;
-
-            FontFamily fontFamily = new FontFamily();
-            // TODO: introduce ttc index and variation settings to resource type font.
-            if (fontFamily.addFontFromAssetManager(mgr, path, cookie, false /* isAsset */,
-                    0 /* ttcIndex */, RESOLVE_BY_FONT_TABLE /* weight */,
-                    RESOLVE_BY_FONT_TABLE /* italic */, null /* axes */)) {
-                if (!fontFamily.freeze()) {
-                    return null;
-                }
-                FontFamily[] families = {fontFamily};
-                typeface = createFromFamiliesWithDefault(families, DEFAULT_FAMILY,
-                        RESOLVE_BY_FONT_TABLE, RESOLVE_BY_FONT_TABLE);
-                sDynamicTypefaceCache.put(key, typeface);
-                return typeface;
-            }
-        }
-        return null;
-    }
-
-    /**
-     * @hide
      * Used by Resources to load a font resource of type xml.
      */
     @Nullable
@@ -258,21 +228,34 @@
         // family is FontFamilyFilesResourceEntry
         final FontFamilyFilesResourceEntry filesEntry = (FontFamilyFilesResourceEntry) entry;
 
-        FontFamily fontFamily = new FontFamily();
-        for (final FontFileResourceEntry fontFile : filesEntry.getEntries()) {
-            if (!fontFamily.addFontFromAssetManager(mgr, fontFile.getFileName(),
-                    0 /* resourceCookie */, false /* isAsset */, fontFile.getTtcIndex(),
-                    fontFile.getWeight(), fontFile.getItalic(),
-                    FontVariationAxis.fromFontVariationSettings(fontFile.getVariationSettings()))) {
-                return null;
+        try {
+            FontFamily.Builder familyBuilder = null;
+            for (final FontFileResourceEntry fontFile : filesEntry.getEntries()) {
+                final Font.Builder fontBuilder = new Font.Builder(mgr, fontFile.getFileName(),
+                        false /* isAsset */, 0 /* cookie */)
+                        .setTtcIndex(fontFile.getTtcIndex())
+                        .setFontVariationSettings(fontFile.getVariationSettings());
+                if (fontFile.getWeight() != Typeface.RESOLVE_BY_FONT_TABLE) {
+                    fontBuilder.setWeight(fontFile.getWeight());
+                }
+                if (fontFile.getItalic() != Typeface.RESOLVE_BY_FONT_TABLE) {
+                    fontBuilder.setSlant(fontFile.getItalic() == FontFileResourceEntry.ITALIC
+                            ?  FontStyle.FONT_SLANT_ITALIC : FontStyle.FONT_SLANT_UPRIGHT);
+                }
+
+                if (familyBuilder == null) {
+                    familyBuilder = new FontFamily.Builder(fontBuilder.build());
+                } else {
+                    familyBuilder.addFont(fontBuilder.build());
+                }
             }
+            if (familyBuilder == null) {
+                return Typeface.DEFAULT;
+            }
+            typeface = new Typeface.CustomFallbackBuilder(familyBuilder.build()).build();
+        } catch (IOException e) {
+            typeface = Typeface.DEFAULT;
         }
-        if (!fontFamily.freeze()) {
-            return null;
-        }
-        FontFamily[] familyChain = { fontFamily };
-        typeface = createFromFamiliesWithDefault(familyChain, DEFAULT_FAMILY,
-                RESOLVE_BY_FONT_TABLE, RESOLVE_BY_FONT_TABLE);
         synchronized (sDynamicCacheLock) {
             final String key = Builder.createAssetUid(mgr, path, 0 /* ttcIndex */,
                     null /* axes */, RESOLVE_BY_FONT_TABLE /* weight */,
@@ -339,15 +322,11 @@
         /** @hide */
         public static final int BOLD_WEIGHT = 700;
 
-        private int mTtcIndex;
-        private FontVariationAxis[] mAxes;
+        // Kept for generating asset cache key.
+        private final AssetManager mAssetManager;
+        private final String mPath;
 
-        private AssetManager mAssetManager;
-        private String mPath;
-        private FileDescriptor mFd;
-
-        private FontsContract.FontInfo[] mFonts;
-        private Map<Uri, ByteBuffer> mFontBuffers;
+        private final Font.Builder mFontBuilder;
 
         private String mFallbackFamilyName;
 
@@ -360,7 +339,9 @@
          * @param path The file object refers to the font file.
          */
         public Builder(@NonNull File path) {
-            mPath = path.getAbsolutePath();
+            mFontBuilder = new Font.Builder(path);
+            mAssetManager = null;
+            mPath = null;
         }
 
         /**
@@ -372,7 +353,9 @@
          * @param fd The file descriptor. The passed fd must be mmap-able.
          */
         public Builder(@NonNull FileDescriptor fd) {
-            mFd = fd;
+            mFontBuilder = new Font.Builder(fd);
+            mAssetManager = null;
+            mPath = null;
         }
 
         /**
@@ -381,7 +364,9 @@
          * @param path The full path to the font file.
          */
         public Builder(@NonNull String path) {
-            mPath = path;
+            mFontBuilder = new Font.Builder(new File(path));
+            mAssetManager = null;
+            mPath = null;
         }
 
         /**
@@ -391,27 +376,22 @@
          * @param path The file name of the font data in the asset directory
          */
         public Builder(@NonNull AssetManager assetManager, @NonNull String path) {
-            mAssetManager = Preconditions.checkNotNull(assetManager);
-            mPath = Preconditions.checkStringNotEmpty(path);
+            this(assetManager, path, true /* is asset */, 0 /* cookie */);
         }
 
         /**
-         * Constracts a builder from an array of FontsContract.FontInfo.
+         * Constructs a builder from an asset manager and a file path in an asset directory.
          *
-         * Since {@link FontsContract.FontInfo} holds information about TTC indices and
-         * variation settings, there is no need to call {@link #setTtcIndex} or
-         * {@link #setFontVariationSettings}. Similary, {@link FontsContract.FontInfo} holds
-         * weight and italic information, so {@link #setWeight} and {@link #setItalic} are used
-         * for style matching during font selection.
-         *
-         * @param fonts The array of {@link FontsContract.FontInfo}
-         * @param buffers The mapping from URI to buffers to be used during building.
+         * @param assetManager The application's asset manager
+         * @param path The file name of the font data in the asset directory
+         * @param cookie a cookie for the asset
          * @hide
          */
-        public Builder(@NonNull FontsContract.FontInfo[] fonts,
-                @NonNull Map<Uri, ByteBuffer> buffers) {
-            mFonts = fonts;
-            mFontBuffers = buffers;
+        public Builder(@NonNull AssetManager assetManager, @NonNull String path, boolean isAsset,
+                int cookie) {
+            mFontBuilder = new Font.Builder(assetManager, path, isAsset, cookie);
+            mAssetManager = assetManager;
+            mPath = path;
         }
 
         /**
@@ -423,6 +403,7 @@
          */
         public Builder setWeight(@IntRange(from = 1, to = 1000) int weight) {
             mWeight = weight;
+            mFontBuilder.setWeight(weight);
             return this;
         }
 
@@ -434,7 +415,8 @@
          * @param italic {@code true} if the font is italic. Otherwise {@code false}.
          */
         public Builder setItalic(boolean italic) {
-            mItalic = italic ? STYLE_ITALIC : STYLE_NORMAL;
+            mItalic = italic ? FontStyle.FONT_SLANT_ITALIC : FontStyle.FONT_SLANT_UPRIGHT;
+            mFontBuilder.setSlant(mItalic);
             return this;
         }
 
@@ -446,11 +428,7 @@
          *                 collection, do not call this method or specify 0.
          */
         public Builder setTtcIndex(@IntRange(from = 0) int ttcIndex) {
-            if (mFonts != null) {
-                throw new IllegalArgumentException(
-                        "TTC index can not be specified for FontResult source.");
-            }
-            mTtcIndex = ttcIndex;
+            mFontBuilder.setTtcIndex(ttcIndex);
             return this;
         }
 
@@ -462,14 +440,7 @@
          *                                  format.
          */
         public Builder setFontVariationSettings(@Nullable String variationSettings) {
-            if (mFonts != null) {
-                throw new IllegalArgumentException(
-                        "Font variation settings can not be specified for FontResult source.");
-            }
-            if (mAxes != null) {
-                throw new IllegalStateException("Font variation settings are already set.");
-            }
-            mAxes = FontVariationAxis.fromFontVariationSettings(variationSettings);
+            mFontBuilder.setFontVariationSettings(variationSettings);
             return this;
         }
 
@@ -479,14 +450,7 @@
          * @param axes An array of font variation axis tag-value pairs.
          */
         public Builder setFontVariationSettings(@Nullable FontVariationAxis[] axes) {
-            if (mFonts != null) {
-                throw new IllegalArgumentException(
-                        "Font variation settings can not be specified for FontResult source.");
-            }
-            if (mAxes != null) {
-                throw new IllegalStateException("Font variation settings are already set.");
-            }
-            mAxes = axes;
+            mFontBuilder.setFontVariationSettings(axes);
             return this;
         }
 
@@ -579,91 +543,41 @@
          * @return Newly created Typeface. May return null if some parameters are invalid.
          */
         public Typeface build() {
-            if (mFd != null) {  // Builder is created with file descriptor.
-                try (FileInputStream fis = new FileInputStream(mFd)) {
-                    FileChannel channel = fis.getChannel();
-                    long size = channel.size();
-                    ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, size);
-
-                    final FontFamily fontFamily = new FontFamily();
-                    if (!fontFamily.addFontFromBuffer(buffer, mTtcIndex, mAxes, mWeight, mItalic)) {
-                        fontFamily.abortCreation();
-                        return resolveFallbackTypeface();
-                    }
-                    if (!fontFamily.freeze()) {
-                        return resolveFallbackTypeface();
-                    }
-                    FontFamily[] families = { fontFamily };
-                    return createFromFamiliesWithDefault(families, mFallbackFamilyName, mWeight,
-                            mItalic);
-                } catch (IOException e) {
-                    return resolveFallbackTypeface();
-                }
-            } else if (mAssetManager != null) {  // Builder is created with asset manager.
-                final String key = createAssetUid(
-                        mAssetManager, mPath, mTtcIndex, mAxes, mWeight, mItalic,
+            try {
+                final Font font = mFontBuilder.build();
+                final String key = mAssetManager == null ? null : createAssetUid(
+                        mAssetManager, mPath, font.getTtcIndex(), font.getAxes(),
+                        font.getStyle().getWeight(), font.getStyle().getSlant(),
                         mFallbackFamilyName);
-                synchronized (sDynamicCacheLock) {
-                    Typeface typeface = sDynamicTypefaceCache.get(key);
-                    if (typeface != null) return typeface;
-                    final FontFamily fontFamily = new FontFamily();
-                    if (!fontFamily.addFontFromAssetManager(mAssetManager, mPath, mTtcIndex,
-                            true /* isAsset */, mTtcIndex, mWeight, mItalic, mAxes)) {
-                        fontFamily.abortCreation();
-                        return resolveFallbackTypeface();
+                if (key != null) {
+                    // Dynamic cache lookup is only for assets.
+                    synchronized (sDynamicCacheLock) {
+                        final Typeface typeface = sDynamicTypefaceCache.get(key);
+                        if (typeface != null) {
+                            return typeface;
+                        }
                     }
-                    if (!fontFamily.freeze()) {
-                        return resolveFallbackTypeface();
+                }
+                final FontFamily family = new FontFamily.Builder(font).build();
+                final int weight = mWeight == RESOLVE_BY_FONT_TABLE
+                        ? font.getStyle().getWeight() : mWeight;
+                final int slant = mItalic == RESOLVE_BY_FONT_TABLE
+                        ? font.getStyle().getSlant() : mItalic;
+                final CustomFallbackBuilder builder = new CustomFallbackBuilder(family)
+                        .setStyle(new FontStyle(weight, slant));
+                if (mFallbackFamilyName != null) {
+                    builder.setFallback(mFallbackFamilyName);
+                }
+                final Typeface typeface = builder.build();
+                if (key != null) {
+                    synchronized (sDynamicCacheLock) {
+                        sDynamicTypefaceCache.put(key, typeface);
                     }
-                    FontFamily[] families = { fontFamily };
-                    typeface = createFromFamiliesWithDefault(families, mFallbackFamilyName,
-                            mWeight, mItalic);
-                    sDynamicTypefaceCache.put(key, typeface);
-                    return typeface;
                 }
-            } else if (mPath != null) {  // Builder is created with file path.
-                final FontFamily fontFamily = new FontFamily();
-                if (!fontFamily.addFont(mPath, mTtcIndex, mAxes, mWeight, mItalic)) {
-                    fontFamily.abortCreation();
-                    return resolveFallbackTypeface();
-                }
-                if (!fontFamily.freeze()) {
-                    return resolveFallbackTypeface();
-                }
-                FontFamily[] families = { fontFamily };
-                return createFromFamiliesWithDefault(families, mFallbackFamilyName, mWeight,
-                        mItalic);
-            } else if (mFonts != null) {
-                final FontFamily fontFamily = new FontFamily();
-                boolean atLeastOneFont = false;
-                for (FontsContract.FontInfo font : mFonts) {
-                    final ByteBuffer fontBuffer = mFontBuffers.get(font.getUri());
-                    if (fontBuffer == null) {
-                        continue;  // skip
-                    }
-                    final boolean success = fontFamily.addFontFromBuffer(fontBuffer,
-                            font.getTtcIndex(), font.getAxes(), font.getWeight(),
-                            font.isItalic() ? STYLE_ITALIC : STYLE_NORMAL);
-                    if (!success) {
-                        fontFamily.abortCreation();
-                        return null;
-                    }
-                    atLeastOneFont = true;
-                }
-                if (!atLeastOneFont) {
-                    // No fonts are avaialble. No need to create new Typeface and returns fallback
-                    // Typeface instead.
-                    fontFamily.abortCreation();
-                    return null;
-                }
-                fontFamily.freeze();
-                FontFamily[] families = { fontFamily };
-                return createFromFamiliesWithDefault(families, mFallbackFamilyName, mWeight,
-                        mItalic);
+                return typeface;
+            } catch (IOException | IllegalArgumentException e) {
+                return resolveFallbackTypeface();
             }
-
-            // Must not reach here.
-            throw new IllegalArgumentException("No source was set.");
         }
     }
 
@@ -713,8 +627,7 @@
         // TODO: Remove package modifier once android.graphics.FontFamily is deprecated.
         private final android.graphics.fonts.FontFamily mFamily;
         private String mFallbackName = null;
-        private @IntRange(from = 0, to = 1000) int mWeight = 400;
-        private boolean mItalic = false;
+        private @Nullable FontStyle mStyle;
 
         /**
          * Constructs a builder with a font family.
@@ -740,35 +653,16 @@
         }
 
         /**
-         * Sets a weight of the Typeface.
+         * Sets a font style of the Typeface.
          *
-         * If the font family doesn't have a font of given weight, system will select the closest
+         * If the font family doesn't have a font of given style, system will select the closest
          * font from font family. For example, if a font family has fonts of 300 weight and 700
          * weight then setWeight(400) is called, system will select the font of 300 weight.
          *
-         * @see Font#FONT_WEIGHT_THIN
-         * @see Font#FONT_WEIGHT_EXTRA_LIGHT
-         * @see Font#FONT_WEIGHT_LIGHT
-         * @see Font#FONT_WEIGHT_NORMAL
-         * @see Font#FONT_WEIGHT_MEDIUM
-         * @see Font#FONT_WEIGHT_SEMI_BOLD
-         * @see Font#FONT_WEIGHT_BOLD
-         * @see Font#FONT_WEIGHT_EXTRA_BOLD
-         * @see Font#FONT_WEIGHT_BLACK
-         * @param weight a weight value
+         * @param style a font style
          */
-        public CustomFallbackBuilder setWeight(@IntRange(from = 0, to = 1000) int weight) {
-            mWeight = weight;
-            return this;
-        }
-
-        /**
-         * Sets a italic style of the Typeface.
-         *
-         * @param italic true if italic, otherwise false
-         */
-        public CustomFallbackBuilder setItalic(boolean italic) {
-            mItalic = italic;
+        public CustomFallbackBuilder setStyle(@NonNull FontStyle style) {
+            mStyle = style;
             return this;
         }
 
@@ -778,14 +672,20 @@
          * @return the Typeface object
          */
         public Typeface build() {
-            final android.graphics.fonts.FontFamily[] fallback =
-                    SystemFonts.getSystemFallback(mFallbackName);
+            final FontFamily[] fallback = SystemFonts.getSystemFallback(mFallbackName);
+            final FontFamily[] fullFamilies = new FontFamily[fallback.length + 1];
             final long[] ptrArray = new long[fallback.length + 1];
             ptrArray[0] = mFamily.getNativePtr();
+            fullFamilies[0] = mFamily;
             for (int i = 0; i < fallback.length; ++i) {
                 ptrArray[i + 1] = fallback[i].getNativePtr();
+                fullFamilies[i + 1] = fallback[i];
             }
-            return new Typeface(nativeCreateFromArray(ptrArray, mWeight, mItalic ? 1 : 0));
+            final int weight = mStyle == null ? 400 : mStyle.getWeight();
+            final int italic =
+                    (mStyle == null || mStyle.getSlant() == FontStyle.FONT_SLANT_UPRIGHT) ?  0 : 1;
+
+            return new Typeface(nativeCreateFromArray(ptrArray, weight, italic), fullFamilies);
         }
     }
 
@@ -850,7 +750,7 @@
                 }
             }
 
-            typeface = new Typeface(nativeCreateFromTypeface(ni, style));
+            typeface = new Typeface(nativeCreateFromTypeface(ni, style), family.mFamilies);
             styles.put(style, typeface);
         }
         return typeface;
@@ -919,7 +819,7 @@
 
             typeface = new Typeface(
                     nativeCreateFromTypefaceWithExactStyle(
-                            base.native_instance, weight, italic));
+                            base.native_instance, weight, italic), base.mFamilies);
             innerCache.put(key, typeface);
         }
         return typeface;
@@ -928,8 +828,9 @@
     /** @hide */
     public static Typeface createFromTypefaceWithVariation(@Nullable Typeface family,
             @NonNull List<FontVariationAxis> axes) {
-        final long ni = family == null ? 0 : family.native_instance;
-        return new Typeface(nativeCreateFromTypefaceWithVariation(ni, axes));
+        final Typeface base = family == null ? Typeface.DEFAULT : family;
+        return new Typeface(nativeCreateFromTypefaceWithVariation(base.native_instance, axes),
+                base.mFamilies);
     }
 
     /**
@@ -1015,7 +916,7 @@
      */
     @Deprecated
     @UnsupportedAppUsage
-    private static Typeface createFromFamilies(FontFamily[] families) {
+    private static Typeface createFromFamilies(android.graphics.FontFamily[] families) {
         long[] ptrArray = new long[families.length];
         for (int i = 0; i < families.length; i++) {
             ptrArray[i] = families[i].mNativePtr;
@@ -1029,14 +930,13 @@
      *
      * @param families array of font families
      */
-    private static Typeface createFromFamilies(
-            @Nullable android.graphics.fonts.FontFamily[] families) {
+    private static Typeface createFromFamilies(@Nullable FontFamily[] families) {
         final long[] ptrArray = new long[families.length];
         for (int i = 0; i < families.length; ++i) {
             ptrArray[i] = families[i].getNativePtr();
         }
         return new Typeface(nativeCreateFromArray(ptrArray,
-                  RESOLVE_BY_FONT_TABLE, RESOLVE_BY_FONT_TABLE));
+                  RESOLVE_BY_FONT_TABLE, RESOLVE_BY_FONT_TABLE), families);
     }
 
     /**
@@ -1044,8 +944,8 @@
      * TODO: Remove private API use in supportlib: http://b/72665240
      */
     @UnsupportedAppUsage
-    private static Typeface createFromFamiliesWithDefault(FontFamily[] families, int weight,
-                int italic) {
+    private static Typeface createFromFamiliesWithDefault(
+            android.graphics.FontFamily[] families, int weight, int italic) {
         return createFromFamiliesWithDefault(families, DEFAULT_FAMILY, weight, italic);
     }
 
@@ -1063,7 +963,7 @@
      * @param families array of font families
      */
     @UnsupportedAppUsage
-    private static Typeface createFromFamiliesWithDefault(FontFamily[] families,
+    private static Typeface createFromFamiliesWithDefault(android.graphics.FontFamily[] families,
                 String fallbackName, int weight, int italic) {
         android.graphics.fonts.FontFamily[] fallback = SystemFonts.getSystemFallback(fallbackName);
         long[] ptrArray = new long[families.length + fallback.length];
@@ -1084,6 +984,19 @@
         }
 
         native_instance = ni;
+        mFamilies = new FontFamily[0];
+        sRegistry.registerNativeAllocation(this, native_instance);
+        mStyle = nativeGetStyle(ni);
+        mWeight = nativeGetWeight(ni);
+    }
+
+    private Typeface(long ni, @NonNull FontFamily[] families) {
+        if (ni == 0) {
+            throw new IllegalStateException("native typeface cannot be made");
+        }
+
+        native_instance = ni;
+        mFamilies = families;
         sRegistry.registerNativeAllocation(this, native_instance);
         mStyle = nativeGetStyle(ni);
         mWeight = nativeGetWeight(ni);
@@ -1097,9 +1010,9 @@
     /** @hide */
     @VisibleForTesting
     public static void initSystemDefaultTypefaces(Map<String, Typeface> systemFontMap,
-            Map<String, android.graphics.fonts.FontFamily[]> fallbacks,
+            Map<String, FontFamily[]> fallbacks,
             FontConfig.Alias[] aliases) {
-        for (Map.Entry<String, android.graphics.fonts.FontFamily[]> entry : fallbacks.entrySet()) {
+        for (Map.Entry<String, FontFamily[]> entry : fallbacks.entrySet()) {
             systemFontMap.put(entry.getKey(), createFromFamilies(entry.getValue()));
         }
 
@@ -1110,7 +1023,8 @@
             final Typeface base = systemFontMap.get(alias.getToName());
             final int weight = alias.getWeight();
             final Typeface newFace = weight == 400 ? base :
-                    new Typeface(nativeCreateWeightAlias(base.native_instance, weight));
+                    new Typeface(nativeCreateWeightAlias(base.native_instance, weight),
+                            base.mFamilies);
             systemFontMap.put(alias.getName(), newFace);
         }
     }
diff --git a/graphics/java/android/graphics/fonts/Font.java b/graphics/java/android/graphics/fonts/Font.java
index 0a8c685..7f165bf 100644
--- a/graphics/java/android/graphics/fonts/Font.java
+++ b/graphics/java/android/graphics/fonts/Font.java
@@ -151,7 +151,21 @@
          * @param path the file name of the font data in the asset directory
          */
         public Builder(@NonNull AssetManager am, @NonNull String path) {
-            final long nativeAsset = nGetNativeAsset(am, path, true /* is asset */, 0 /* cookie */);
+            this(am, path, true /* is asset */, 0 /* cookie */);
+        }
+
+        /**
+         * Constructs a builder from an asset manager and a file path in an asset directory.
+         *
+         * @param am the application's asset manager
+         * @param path the file name of the font data in the asset directory
+         * @param isAsset true if the undelying data is in asset
+         * @param cookie set asset cookie
+         * @hide
+         */
+        public Builder(@NonNull AssetManager am, @NonNull String path, boolean isAsset,
+                int cookie) {
+            final long nativeAsset = nGetNativeAsset(am, path, isAsset, cookie);
             if (nativeAsset == 0) {
                 mException = new FileNotFoundException("Unable to open " + path);
                 return;
@@ -293,7 +307,7 @@
          * will resolve the style by reading font tables.
          *
          * For example, if you want to use italic font as upright font, call {@code
-         * setSlant(false)} explicitly.
+         * setSlant(FontStyle.FONT_SLANT_UPRIGHT)} explicitly.
          *
          * @return this builder
          */
@@ -447,23 +461,14 @@
     }
 
     /**
-     * Get a weight value associated with this font.
+     * Get a style associated with this font.
      *
      * @see Builder#setWeight(int)
-     * @return a weight value
+     * @see Builder#setSlant(int)
+     * @return a font style
      */
-    public @IntRange(from = 0, to = 1000)int getWeight() {
-        return mFontStyle.getWeight();
-    }
-
-    /**
-     * Get a slant value associated with this font.
-     *
-     * @see Builder#setSlant(boolean)
-     * @return a slant value
-     */
-    public @FontStyle.FontSlant int getSlant() {
-        return mFontStyle.getSlant();
+    public FontStyle getStyle() {
+        return mFontStyle;
     }
 
     /**
diff --git a/graphics/java/android/graphics/fonts/FontFamily.java b/graphics/java/android/graphics/fonts/FontFamily.java
index 52a37da..14d31d9 100644
--- a/graphics/java/android/graphics/fonts/FontFamily.java
+++ b/graphics/java/android/graphics/fonts/FontFamily.java
@@ -124,7 +124,7 @@
         }
 
         private static int makeStyleIdentifier(@NonNull Font font) {
-            return font.getWeight() | (font.getSlant()  << 16);
+            return font.getStyle().getWeight() | (font.getStyle().getSlant()  << 16);
         }
 
         private static native long nInitBuilder();
diff --git a/libs/hwui/pipeline/skia/SkiaRecordingCanvas.cpp b/libs/hwui/pipeline/skia/SkiaRecordingCanvas.cpp
index 3fa73a4..596b8af 100644
--- a/libs/hwui/pipeline/skia/SkiaRecordingCanvas.cpp
+++ b/libs/hwui/pipeline/skia/SkiaRecordingCanvas.cpp
@@ -81,6 +81,11 @@
 }
 
 void SkiaRecordingCanvas::insertReorderBarrier(bool enableReorder) {
+    if (mCurrentBarrier && enableReorder) {
+        // Already in a re-order section, nothing to do
+        return;
+    }
+
     if (nullptr != mCurrentBarrier) {
         // finish off the existing chunk
         SkDrawable* drawable =
@@ -89,9 +94,8 @@
         drawDrawable(drawable);
     }
     if (enableReorder) {
-        mCurrentBarrier = (StartReorderBarrierDrawable*)
-                                  mDisplayList->allocateDrawable<StartReorderBarrierDrawable>(
-                                          mDisplayList.get());
+        mCurrentBarrier = mDisplayList->allocateDrawable<StartReorderBarrierDrawable>(
+                mDisplayList.get());
         drawDrawable(mCurrentBarrier);
     }
 }
diff --git a/libs/hwui/service/GraphicsStatsService.cpp b/libs/hwui/service/GraphicsStatsService.cpp
index 3d50d2d..fb1fde2 100644
--- a/libs/hwui/service/GraphicsStatsService.cpp
+++ b/libs/hwui/service/GraphicsStatsService.cpp
@@ -232,9 +232,9 @@
         return;
     }
     dprintf(fd, "\nPackage: %s", proto->package_name().c_str());
-    dprintf(fd, "\nVersion: %lld", proto->version_code());
-    dprintf(fd, "\nStats since: %lldns", proto->stats_start());
-    dprintf(fd, "\nStats end: %lldns", proto->stats_end());
+    dprintf(fd, "\nVersion: %" PRId64, proto->version_code());
+    dprintf(fd, "\nStats since: %" PRId64 "ns", proto->stats_start());
+    dprintf(fd, "\nStats end: %" PRId64 "ns", proto->stats_end());
     auto summary = proto->summary();
     dprintf(fd, "\nTotal frames rendered: %d", summary.total_frames());
     dprintf(fd, "\nJanky frames: %d (%.2f%%)", summary.janky_frames(),
diff --git a/libs/hwui/tests/macrobench/TestSceneRunner.cpp b/libs/hwui/tests/macrobench/TestSceneRunner.cpp
index 9428f53..5f5a92e 100644
--- a/libs/hwui/tests/macrobench/TestSceneRunner.cpp
+++ b/libs/hwui/tests/macrobench/TestSceneRunner.cpp
@@ -81,11 +81,11 @@
     // mean and stddev which doesn't make sense for our usage
     std::vector<BenchmarkReporter::Run> reports;
     BenchmarkReporter::Run report;
-    report.benchmark_name = info.name;
+    report.run_name = info.name;
     report.iterations = static_cast<int64_t>(opts.count);
     report.real_accumulated_time = durationInS;
     report.cpu_accumulated_time = durationInS;
-    report.items_per_second = opts.count / durationInS;
+    report.counters["items_per_second"] = opts.count / durationInS;
     reports.push_back(report);
     reporter->ReportRuns(reports);
 
@@ -94,13 +94,13 @@
     // in that test case than percentiles.
     if (!opts.renderOffscreen) {
         for (auto& ri : REPORTS) {
-            reports[0].benchmark_name = info.name;
-            reports[0].benchmark_name += ri.suffix;
+            reports[0].run_name = info.name;
+            reports[0].run_name += ri.suffix;
             durationInS = proxy->frameTimePercentile(ri.percentile) / 1000.0;
             reports[0].real_accumulated_time = durationInS;
             reports[0].cpu_accumulated_time = durationInS;
             reports[0].iterations = 1;
-            reports[0].items_per_second = 0;
+            reports[0].counters["items_per_second"] = 0;
             reporter->ReportRuns(reports);
         }
     }
diff --git a/libs/protoutil/include/android/util/ProtoOutputStream.h b/libs/protoutil/include/android/util/ProtoOutputStream.h
index ad76559..0377426 100644
--- a/libs/protoutil/include/android/util/ProtoOutputStream.h
+++ b/libs/protoutil/include/android/util/ProtoOutputStream.h
@@ -97,6 +97,7 @@
     bool write(uint64_t fieldId, double val);
     bool write(uint64_t fieldId, float val);
     bool write(uint64_t fieldId, int val);
+    bool write(uint64_t fieldId, long val);
     bool write(uint64_t fieldId, long long val);
     bool write(uint64_t fieldId, bool val);
     bool write(uint64_t fieldId, std::string val);
diff --git a/libs/protoutil/src/ProtoOutputStream.cpp b/libs/protoutil/src/ProtoOutputStream.cpp
index ff3fad6..0c62d52 100644
--- a/libs/protoutil/src/ProtoOutputStream.cpp
+++ b/libs/protoutil/src/ProtoOutputStream.cpp
@@ -116,6 +116,34 @@
 }
 
 bool
+ProtoOutputStream::write(uint64_t fieldId, long val)
+{
+    if (mCompact) return false;
+    const uint32_t id = (uint32_t)fieldId;
+    switch (fieldId & FIELD_TYPE_MASK) {
+        case FIELD_TYPE_DOUBLE:   writeDoubleImpl(id, (double)val);           break;
+        case FIELD_TYPE_FLOAT:    writeFloatImpl(id, (float)val);             break;
+        case FIELD_TYPE_INT64:    writeInt64Impl(id, (long long)val);         break;
+        case FIELD_TYPE_UINT64:   writeUint64Impl(id, (uint64_t)val);         break;
+        case FIELD_TYPE_INT32:    writeInt32Impl(id, (int)val);               break;
+        case FIELD_TYPE_FIXED64:  writeFixed64Impl(id, (uint64_t)val);        break;
+        case FIELD_TYPE_FIXED32:  writeFixed32Impl(id, (uint32_t)val);        break;
+        case FIELD_TYPE_UINT32:   writeUint32Impl(id, (uint32_t)val);         break;
+        case FIELD_TYPE_SFIXED32: writeSFixed32Impl(id, (int)val);            break;
+        case FIELD_TYPE_SFIXED64: writeSFixed64Impl(id, (long long)val);      break;
+        case FIELD_TYPE_SINT32:   writeZigzagInt32Impl(id, (int)val);         break;
+        case FIELD_TYPE_SINT64:   writeZigzagInt64Impl(id, (long long)val);   break;
+        case FIELD_TYPE_ENUM:     writeEnumImpl(id, (int)val);                break;
+        case FIELD_TYPE_BOOL:     writeBoolImpl(id, val != 0);                break;
+        default:
+            ALOGW("Field type %d is not supported when writing long val.",
+                    (int)((fieldId & FIELD_TYPE_MASK) >> FIELD_TYPE_SHIFT));
+            return false;
+    }
+    return true;
+}
+
+bool
 ProtoOutputStream::write(uint64_t fieldId, long long val)
 {
     return internalWrite(fieldId, val, "long long");
diff --git a/media/java/android/media/AudioFormat.java b/media/java/android/media/AudioFormat.java
index b34f270..3e3e651 100644
--- a/media/java/android/media/AudioFormat.java
+++ b/media/java/android/media/AudioFormat.java
@@ -273,6 +273,11 @@
      * supports {@link #ENCODING_E_AC3} but not {@link #ENCODING_E_AC3_JOC}.
      **/
     public static final int ENCODING_E_AC3_JOC = 18;
+    /** Audio data format: Dolby MAT (Metadata-enhanced Audio Transmission)
+     * Dolby MAT bitstreams are used to transmit Dolby TrueHD, channel-based PCM, or PCM with
+     * metadata (object audio) over HDMI (e.g. Dolby Atmos content).
+     **/
+    public static final int ENCODING_DOLBY_MAT = 19;
 
     /** @hide */
     public static String toLogFriendlyEncoding(int enc) {
@@ -313,6 +318,8 @@
                 return "ENCODING_AC4";
             case ENCODING_E_AC3_JOC:
                 return "ENCODING_E_AC3_JOC";
+            case ENCODING_DOLBY_MAT:
+                return "ENCODING_DOLBY_MAT";
             default :
                 return "invalid encoding " + enc;
         }
@@ -520,26 +527,27 @@
     public static boolean isValidEncoding(int audioFormat)
     {
         switch (audioFormat) {
-        case ENCODING_PCM_16BIT:
-        case ENCODING_PCM_8BIT:
-        case ENCODING_PCM_FLOAT:
-        case ENCODING_AC3:
-        case ENCODING_E_AC3:
-        case ENCODING_DTS:
-        case ENCODING_DTS_HD:
-        case ENCODING_MP3:
-        case ENCODING_AAC_LC:
-        case ENCODING_AAC_HE_V1:
-        case ENCODING_AAC_HE_V2:
-        case ENCODING_IEC61937:
-        case ENCODING_DOLBY_TRUEHD:
-        case ENCODING_AAC_ELD:
-        case ENCODING_AAC_XHE:
-        case ENCODING_AC4:
-        case ENCODING_E_AC3_JOC:
-            return true;
-        default:
-            return false;
+            case ENCODING_PCM_16BIT:
+            case ENCODING_PCM_8BIT:
+            case ENCODING_PCM_FLOAT:
+            case ENCODING_AC3:
+            case ENCODING_E_AC3:
+            case ENCODING_DTS:
+            case ENCODING_DTS_HD:
+            case ENCODING_MP3:
+            case ENCODING_AAC_LC:
+            case ENCODING_AAC_HE_V1:
+            case ENCODING_AAC_HE_V2:
+            case ENCODING_IEC61937:
+            case ENCODING_DOLBY_TRUEHD:
+            case ENCODING_AAC_ELD:
+            case ENCODING_AAC_XHE:
+            case ENCODING_AC4:
+            case ENCODING_E_AC3_JOC:
+            case ENCODING_DOLBY_MAT:
+                return true;
+            default:
+                return false;
         }
     }
 
@@ -547,26 +555,27 @@
     public static boolean isPublicEncoding(int audioFormat)
     {
         switch (audioFormat) {
-        case ENCODING_PCM_16BIT:
-        case ENCODING_PCM_8BIT:
-        case ENCODING_PCM_FLOAT:
-        case ENCODING_AC3:
-        case ENCODING_E_AC3:
-        case ENCODING_DTS:
-        case ENCODING_DTS_HD:
-        case ENCODING_MP3:
-        case ENCODING_AAC_LC:
-        case ENCODING_AAC_HE_V1:
-        case ENCODING_AAC_HE_V2:
-        case ENCODING_IEC61937:
-        case ENCODING_DOLBY_TRUEHD:
-        case ENCODING_AAC_ELD:
-        case ENCODING_AAC_XHE:
-        case ENCODING_AC4:
-        case ENCODING_E_AC3_JOC:
-            return true;
-        default:
-            return false;
+            case ENCODING_PCM_16BIT:
+            case ENCODING_PCM_8BIT:
+            case ENCODING_PCM_FLOAT:
+            case ENCODING_AC3:
+            case ENCODING_E_AC3:
+            case ENCODING_DTS:
+            case ENCODING_DTS_HD:
+            case ENCODING_MP3:
+            case ENCODING_AAC_LC:
+            case ENCODING_AAC_HE_V1:
+            case ENCODING_AAC_HE_V2:
+            case ENCODING_IEC61937:
+            case ENCODING_DOLBY_TRUEHD:
+            case ENCODING_AAC_ELD:
+            case ENCODING_AAC_XHE:
+            case ENCODING_AC4:
+            case ENCODING_E_AC3_JOC:
+            case ENCODING_DOLBY_MAT:
+                return true;
+            default:
+                return false;
         }
     }
 
@@ -575,29 +584,30 @@
     public static boolean isEncodingLinearPcm(int audioFormat)
     {
         switch (audioFormat) {
-        case ENCODING_PCM_16BIT:
-        case ENCODING_PCM_8BIT:
-        case ENCODING_PCM_FLOAT:
-        case ENCODING_DEFAULT:
-            return true;
-        case ENCODING_AC3:
-        case ENCODING_E_AC3:
-        case ENCODING_DTS:
-        case ENCODING_DTS_HD:
-        case ENCODING_MP3:
-        case ENCODING_AAC_LC:
-        case ENCODING_AAC_HE_V1:
-        case ENCODING_AAC_HE_V2:
-        case ENCODING_IEC61937: // wrapped in PCM but compressed
-        case ENCODING_DOLBY_TRUEHD:
-        case ENCODING_AAC_ELD:
-        case ENCODING_AAC_XHE:
-        case ENCODING_AC4:
-        case ENCODING_E_AC3_JOC:
-            return false;
-        case ENCODING_INVALID:
-        default:
-            throw new IllegalArgumentException("Bad audio format " + audioFormat);
+            case ENCODING_PCM_16BIT:
+            case ENCODING_PCM_8BIT:
+            case ENCODING_PCM_FLOAT:
+            case ENCODING_DEFAULT:
+                return true;
+            case ENCODING_AC3:
+            case ENCODING_E_AC3:
+            case ENCODING_DTS:
+            case ENCODING_DTS_HD:
+            case ENCODING_MP3:
+            case ENCODING_AAC_LC:
+            case ENCODING_AAC_HE_V1:
+            case ENCODING_AAC_HE_V2:
+            case ENCODING_IEC61937: // wrapped in PCM but compressed
+            case ENCODING_DOLBY_TRUEHD:
+            case ENCODING_AAC_ELD:
+            case ENCODING_AAC_XHE:
+            case ENCODING_AC4:
+            case ENCODING_E_AC3_JOC:
+            case ENCODING_DOLBY_MAT:
+                return false;
+            case ENCODING_INVALID:
+            default:
+                throw new IllegalArgumentException("Bad audio format " + audioFormat);
         }
     }
 
@@ -605,29 +615,30 @@
     public static boolean isEncodingLinearFrames(int audioFormat)
     {
         switch (audioFormat) {
-        case ENCODING_PCM_16BIT:
-        case ENCODING_PCM_8BIT:
-        case ENCODING_PCM_FLOAT:
-        case ENCODING_IEC61937: // same size as stereo PCM
-        case ENCODING_DEFAULT:
-            return true;
-        case ENCODING_AC3:
-        case ENCODING_E_AC3:
-        case ENCODING_DTS:
-        case ENCODING_DTS_HD:
-        case ENCODING_MP3:
-        case ENCODING_AAC_LC:
-        case ENCODING_AAC_HE_V1:
-        case ENCODING_AAC_HE_V2:
-        case ENCODING_DOLBY_TRUEHD:
-        case ENCODING_AAC_ELD:
-        case ENCODING_AAC_XHE:
-        case ENCODING_AC4:
-        case ENCODING_E_AC3_JOC:
-            return false;
-        case ENCODING_INVALID:
-        default:
-            throw new IllegalArgumentException("Bad audio format " + audioFormat);
+            case ENCODING_PCM_16BIT:
+            case ENCODING_PCM_8BIT:
+            case ENCODING_PCM_FLOAT:
+            case ENCODING_IEC61937: // same size as stereo PCM
+            case ENCODING_DEFAULT:
+                return true;
+            case ENCODING_AC3:
+            case ENCODING_E_AC3:
+            case ENCODING_DTS:
+            case ENCODING_DTS_HD:
+            case ENCODING_MP3:
+            case ENCODING_AAC_LC:
+            case ENCODING_AAC_HE_V1:
+            case ENCODING_AAC_HE_V2:
+            case ENCODING_DOLBY_TRUEHD:
+            case ENCODING_AAC_ELD:
+            case ENCODING_AAC_XHE:
+            case ENCODING_AC4:
+            case ENCODING_E_AC3_JOC:
+            case ENCODING_DOLBY_MAT:
+                return false;
+            case ENCODING_INVALID:
+            default:
+                throw new IllegalArgumentException("Bad audio format " + audioFormat);
         }
     }
     /**
@@ -867,6 +878,7 @@
                 case ENCODING_AAC_XHE:
                 case ENCODING_AC4:
                 case ENCODING_E_AC3_JOC:
+                case ENCODING_DOLBY_MAT:
                     mEncoding = encoding;
                     break;
                 case ENCODING_INVALID:
@@ -1083,7 +1095,8 @@
         ENCODING_AAC_ELD,
         ENCODING_AAC_XHE,
         ENCODING_AC4,
-        ENCODING_E_AC3_JOC }
+        ENCODING_E_AC3_JOC,
+        ENCODING_DOLBY_MAT }
     )
     @Retention(RetentionPolicy.SOURCE)
     public @interface Encoding {}
@@ -1098,6 +1111,7 @@
             ENCODING_DOLBY_TRUEHD,
             ENCODING_AC4,
             ENCODING_E_AC3_JOC,
+            ENCODING_DOLBY_MAT,
     };
 
     /** @hide */
@@ -1109,7 +1123,8 @@
             ENCODING_AAC_LC,
             ENCODING_DOLBY_TRUEHD,
             ENCODING_AC4,
-            ENCODING_E_AC3_JOC }
+            ENCODING_E_AC3_JOC,
+            ENCODING_DOLBY_MAT }
     )
     @Retention(RetentionPolicy.SOURCE)
     public @interface SurroundSoundEncoding {}
@@ -1141,6 +1156,8 @@
                 return "Dolby AC-4";
             case ENCODING_E_AC3_JOC:
                 return "Dolby Atmos in Dolby Digital Plus";
+            case ENCODING_DOLBY_MAT:
+                return "Dolby MAT";
             default:
                 return "Unknown surround sound format";
         }
diff --git a/media/java/android/media/MediaMetadataRetriever.java b/media/java/android/media/MediaMetadataRetriever.java
index e019f42..00a393a 100644
--- a/media/java/android/media/MediaMetadataRetriever.java
+++ b/media/java/android/media/MediaMetadataRetriever.java
@@ -958,4 +958,16 @@
      */
     public static final int METADATA_KEY_COLOR_RANGE    = 37;
     // Add more here...
+
+    /**
+     * This key retrieves the sample rate, if available.
+     * @hide
+     */
+    public static final int METADATA_KEY_SAMPLERATE      = 38;
+
+    /**
+     * This key retrieves the bits per sample, if available.
+     * @hide
+     */
+    public static final int METADATA_KEY_BITS_PER_SAMPLE = 39;
 }
diff --git a/media/jni/Android.bp b/media/jni/Android.bp
index fa9ab1f..0f531c9 100644
--- a/media/jni/Android.bp
+++ b/media/jni/Android.bp
@@ -123,14 +123,12 @@
         "libcutils",
         "libmedia_helper",
         "libmedia_player2_util",
-        "libmediadrm",
         "libmediaextractor",
         "libmediametrics",
         "libmediaplayer2",
         "libmediaplayer2-protos",
         "libmediandk_utils",
         "libmediautils",
-        "libnetd_client",  // for setNetworkForUser
         "libprotobuf-cpp-lite",
         "libstagefright_esds",
         "libstagefright_foundation",
@@ -139,7 +137,7 @@
         "libstagefright_mpeg2support",
         "libstagefright_nuplayer2",
         "libstagefright_player2",
-        "libstagefright_rtsp",
+        "libstagefright_rtsp_player2",
         "libstagefright_timedtext2",
         "libmedia2_jni_core",
     ],
diff --git a/packages/ExtServices/src/android/ext/services/notification/Assistant.java b/packages/ExtServices/src/android/ext/services/notification/Assistant.java
index 8f33a70..ddc00e3 100644
--- a/packages/ExtServices/src/android/ext/services/notification/Assistant.java
+++ b/packages/ExtServices/src/android/ext/services/notification/Assistant.java
@@ -38,6 +38,7 @@
 import android.os.Bundle;
 import android.os.Environment;
 import android.os.Handler;
+import android.os.SystemProperties;
 import android.os.UserHandle;
 import android.os.storage.StorageManager;
 import android.provider.Settings;
@@ -77,6 +78,10 @@
 public class Assistant extends NotificationAssistantService {
     private static final String TAG = "ExtAssistant";
     private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
+    public static final boolean AUTO_DEMOTE_NOTIFICATIONS = SystemProperties.getBoolean(
+            "debug.demote_notifs", false);
+    public static final boolean AGE_NOTIFICATIONS = SystemProperties.getBoolean(
+            "debug.age_notifs", false);
 
     private static final String TAG_ASSISTANT = "assistant";
     private static final String TAG_IMPRESSION = "impression-set";
@@ -230,16 +235,19 @@
             @NonNull ArrayList<Notification.Action> smartActions,
             @NonNull ArrayList<CharSequence> smartReplies) {
         Bundle signals = new Bundle();
-        if (!smartActions.isEmpty()) {
-            signals.putParcelableArrayList(Adjustment.KEY_SMART_ACTIONS, smartActions);
-        }
-        if (!smartReplies.isEmpty()) {
-            signals.putCharSequenceArrayList(Adjustment.KEY_SMART_REPLIES, smartReplies);
-        }
-        if (mNotificationCategorizer.shouldSilence(entry)) {
-            final int importance = entry.getImportance() < IMPORTANCE_LOW ? entry.getImportance()
-                    : IMPORTANCE_LOW;
-            signals.putInt(KEY_IMPORTANCE, importance);
+
+        if (AUTO_DEMOTE_NOTIFICATIONS) {
+            if (!smartActions.isEmpty()) {
+                signals.putParcelableArrayList(Adjustment.KEY_SMART_ACTIONS, smartActions);
+            }
+            if (!smartReplies.isEmpty()) {
+                signals.putCharSequenceArrayList(Adjustment.KEY_SMART_REPLIES, smartReplies);
+            }
+            if (mNotificationCategorizer.shouldSilence(entry)) {
+                final int importance = entry.getImportance() < IMPORTANCE_LOW
+                        ? entry.getImportance() : IMPORTANCE_LOW;
+                signals.putInt(KEY_IMPORTANCE, importance);
+            }
         }
 
         return new Adjustment(
@@ -445,13 +453,15 @@
     protected final class AgingCallback implements Callback {
         @Override
         public void sendAdjustment(String key, int newImportance) {
-            NotificationEntry entry = mLiveNotifications.get(key);
-            if (entry != null) {
-                Bundle bundle = new Bundle();
-                bundle.putInt(KEY_IMPORTANCE, newImportance);
-                Adjustment adjustment = new Adjustment(entry.getSbn().getPackageName(), key, bundle,
-                        "aging", entry.getSbn().getUserId());
-                adjustNotification(adjustment);
+            if (AGE_NOTIFICATIONS) {
+                NotificationEntry entry = mLiveNotifications.get(key);
+                if (entry != null) {
+                    Bundle bundle = new Bundle();
+                    bundle.putInt(KEY_IMPORTANCE, newImportance);
+                    Adjustment adjustment = new Adjustment(entry.getSbn().getPackageName(), key,
+                            bundle, "aging", entry.getSbn().getUserId());
+                    adjustNotification(adjustment);
+                }
             }
         }
     }
diff --git a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
index c996620..2d43762 100644
--- a/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
+++ b/packages/SettingsProvider/src/com/android/providers/settings/SettingsProtoDumpUtil.java
@@ -672,6 +672,9 @@
         dumpSetting(s, p,
                 Settings.Global.GPU_DEBUG_LAYER_APP,
                 GlobalSettingsProto.Gpu.DEBUG_LAYER_APP);
+        dumpSetting(s, p,
+                Settings.Global.GPU_DEBUG_LAYERS_GLES,
+                GlobalSettingsProto.Gpu.DEBUG_LAYERS_GLES);
         p.end(gpuToken);
 
         final long hdmiToken = p.start(GlobalSettingsProto.HDMI);
diff --git a/packages/SystemUI/res/drawable/privacy_chip_bg.xml b/packages/SystemUI/res/drawable/privacy_chip_bg.xml
new file mode 100644
index 0000000..8247c27
--- /dev/null
+++ b/packages/SystemUI/res/drawable/privacy_chip_bg.xml
@@ -0,0 +1,22 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2018 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<shape xmlns:android="http://schemas.android.com/apk/res/android">
+    <solid android:color="#bbbbbb" />
+    <padding android:padding="@dimen/ongoing_appops_chip_bg_padding" />
+    <corners android:radius="@dimen/ongoing_appops_chip_bg_corner_radius" />
+</shape>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/ongoing_privacy_chip.xml b/packages/SystemUI/res/layout/ongoing_privacy_chip.xml
new file mode 100644
index 0000000..5e952e3
--- /dev/null
+++ b/packages/SystemUI/res/layout/ongoing_privacy_chip.xml
@@ -0,0 +1,44 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2018 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<com.android.systemui.privacy.OngoingPrivacyChip
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:id="@+id/privacy_chip"
+    android:layout_width="wrap_content"
+    android:layout_height="match_parent"
+    android:layout_margin="@dimen/ongoing_appops_chip_margin"
+    android:gravity="center_vertical|end"
+    android:orientation="horizontal"
+    android:paddingStart="@dimen/ongoing_appops_chip_side_padding"
+    android:paddingEnd="@dimen/ongoing_appops_chip_side_padding"
+    android:background="@drawable/privacy_chip_bg"
+    android:focusable="true">
+
+        <LinearLayout
+            android:id="@+id/icons_container"
+            android:layout_height="match_parent"
+            android:layout_width="wrap_content"
+            android:gravity="center_vertical|start"
+            />
+
+        <TextView
+            android:id="@+id/app_name"
+            android:layout_height="match_parent"
+            android:layout_width="wrap_content"
+            android:gravity="center_vertical|end"
+        />
+</com.android.systemui.privacy.OngoingPrivacyChip>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/ongoing_privacy_dialog_content.xml b/packages/SystemUI/res/layout/ongoing_privacy_dialog_content.xml
new file mode 100644
index 0000000..b5e24a0
--- /dev/null
+++ b/packages/SystemUI/res/layout/ongoing_privacy_dialog_content.xml
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2018 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+            android:id="@+id/container"
+            android:layout_width="match_parent"
+            android:layout_height="match_parent"
+            android:fillViewport ="true"
+            android:orientation="vertical">
+
+    <LinearLayout
+        android:id="@+id/dialog_container"
+        android:layout_width="match_parent"
+        android:layout_height="match_parent"
+        android:orientation="vertical"
+        android:padding="@dimen/ongoing_appops_dialog_content_padding">
+
+        <LinearLayout
+            android:id="@+id/icons_container"
+            android:layout_width="match_parent"
+            android:layout_height="@dimen/ongoing_appops_dialog_icon_height"
+            android:orientation="horizontal"
+            android:gravity="center"
+            android:importantForAccessibility="no"
+        />
+
+        <LinearLayout
+            android:id="@+id/text_container"
+            android:layout_width="match_parent"
+            android:layout_height="wrap_content"
+            android:orientation="vertical"
+            android:gravity="start"
+        />
+    </LinearLayout>
+
+</ScrollView>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/ongoing_privacy_text_item.xml b/packages/SystemUI/res/layout/ongoing_privacy_text_item.xml
new file mode 100644
index 0000000..5595b13
--- /dev/null
+++ b/packages/SystemUI/res/layout/ongoing_privacy_text_item.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!--
+     Copyright (C) 2018 The Android Open Source Project
+
+     Licensed under the Apache License, Version 2.0 (the "License");
+     you may not use this file except in compliance with the License.
+     You may obtain a copy of the License at
+
+          http://www.apache.org/licenses/LICENSE-2.0
+
+     Unless required by applicable law or agreed to in writing, software
+     distributed under the License is distributed on an "AS IS" BASIS,
+     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+     See the License for the specific language governing permissions and
+     limitations under the License.
+-->
+
+<TextView
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="match_parent"
+    android:layout_height="wrap_content"
+    android:textDirection="locale"
+    android:textAppearance="@style/TextAppearance.QS.DetailItemPrimary"
+/>
\ No newline at end of file
diff --git a/packages/SystemUI/res/layout/quick_status_bar_header_system_icons.xml b/packages/SystemUI/res/layout/quick_status_bar_header_system_icons.xml
index 680112c..007070e 100644
--- a/packages/SystemUI/res/layout/quick_status_bar_header_system_icons.xml
+++ b/packages/SystemUI/res/layout/quick_status_bar_header_system_icons.xml
@@ -46,6 +46,8 @@
         android:layout_weight="1"
         android:gravity="center_vertical|center_horizontal" />
 
+    <include layout="@layout/ongoing_privacy_chip" />
+
     <com.android.systemui.BatteryMeterView
         android:id="@+id/battery"
         android:layout_height="match_parent"
diff --git a/packages/SystemUI/res/values/config.xml b/packages/SystemUI/res/values/config.xml
index b31dc50..c61b1d2 100644
--- a/packages/SystemUI/res/values/config.xml
+++ b/packages/SystemUI/res/values/config.xml
@@ -461,5 +461,7 @@
     <bool name="config_pipEnableDismissDragToEdge">true</bool>
 
     <!-- SystemUI Plugins that can be loaded on user builds. -->
-    <string-array name="config_pluginWhitelist" translatable="false" />
+    <string-array name="config_pluginWhitelist" translatable="false">
+        <item>com.android.systemui</item>
+    </string-array>
 </resources>
diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml
index f77d923..525421a 100644
--- a/packages/SystemUI/res/values/dimens.xml
+++ b/packages/SystemUI/res/values/dimens.xml
@@ -932,4 +932,19 @@
     <!-- How much we expand the touchable region of the status bar below the notch to catch touches
          that just start below the notch. -->
     <dimen name="display_cutout_touchable_region_size">12dp</dimen>
+
+    <!-- Height of icons in Ongoing App Ops dialog. Both App Op icon and application icon -->
+    <dimen name="ongoing_appops_dialog_icon_height">48dp</dimen>
+    <!-- Margin between text lines in Ongoing App Ops dialog -->
+    <dimen name="ongoing_appops_dialog_text_margin">15dp</dimen>
+    <!-- Padding around Ongoing App Ops dialog content -->
+    <dimen name="ongoing_appops_dialog_content_padding">24dp</dimen>
+    <!-- Margins around the Ongoing App Ops chip. In landscape, the side margins are 0 -->
+    <dimen name="ongoing_appops_chip_margin">12dp</dimen>
+    <!-- Start and End padding for Ongoing App Ops chip -->
+    <dimen name="ongoing_appops_chip_side_padding">6dp</dimen>
+    <!-- Padding between background of Ongoing App Ops chip and content -->
+    <dimen name="ongoing_appops_chip_bg_padding">4dp</dimen>
+    <!-- Radius of Ongoing App Ops chip corners -->
+    <dimen name="ongoing_appops_chip_bg_corner_radius">12dp</dimen>
 </resources>
diff --git a/packages/SystemUI/res/values/strings.xml b/packages/SystemUI/res/values/strings.xml
index d678412..7d09c00 100644
--- a/packages/SystemUI/res/values/strings.xml
+++ b/packages/SystemUI/res/values/strings.xml
@@ -2238,4 +2238,39 @@
          app for debugging. Will not be seen by users. [CHAR LIMIT=20] -->
     <string name="heap_dump_tile_name">Dump SysUI Heap</string>
 
+    <!-- Content description for ongoing privacy chip. Use with a single app [CHAR LIMIT=NONE]-->
+    <string name="ongoing_privacy_chip_content_single_app"><xliff:g id="app" example="Example App">%1$s</xliff:g> is using your <xliff:g id="types_list" example="camera, location">%2$s</xliff:g>.</string>
+
+    <!-- Content description for ongoing privacy chip. Use with multiple apps [CHAR LIMIT=NONE]-->
+    <string name="ongoing_privacy_chip_content_multiple_apps">Applications are using your <xliff:g id="types_list" example="camera, location">%s</xliff:g>.</string>
+
+    <!-- Action on Ongoing Privacy Dialog to open application [CHAR LIMIT=10]-->
+    <string name="ongoing_privacy_dialog_open_app">Open app</string>
+
+    <!-- Action on Ongoing Privacy Dialog to dismiss [CHAR LIMIT=10]-->
+    <string name="ongoing_privacy_dialog_cancel">Cancel</string>
+
+    <!-- Action on Ongoing Privacy Dialog to dismiss [CHAR LIMIT=10]-->
+    <string name="ongoing_privacy_dialog_okay">Okay</string>
+
+    <!-- Action on Ongoing Privacy Dialog to open privacy hub [CHAR LIMIT=10]-->
+    <string name="ongoing_privacy_dialog_open_settings">Settings</string>
+
+    <!-- Text for item in Ongoing Privacy Dialog when only one app is using a particular type of app op [CHAR LIMIT=NONE] -->
+    <string name="ongoing_privacy_dialog_app_item"><xliff:g id="app" example="Example App">%1$s</xliff:g> is using your <xliff:g id="type" example="camera">%2$s</xliff:g> for the last <xliff:g id="time" example="3">%3$d</xliff:g> min</string>
+
+    <!-- Text for item in Ongoing Privacy Dialog when only multiple apps are using a particular type of app op [CHAR LIMIT=NONE] -->
+    <string name="ongoing_privacy_dialog_apps_item"><xliff:g id="apps" example="Camera, Phone">%1$s</xliff:g> are using your <xliff:g id="type" example="camera">%2$s</xliff:g></string>
+
+    <!-- Text for Ongoing Privacy Dialog when a single app is using app ops [CHAR LIMIT=NONE] -->
+    <string name="ongoing_privacy_dialog_single_app"><xliff:g id="app" example="Example App">%1$s</xliff:g> is using your <xliff:g id="types_list" example="camera, location">%2$s</xliff:g></string>
+
+    <!-- Text for camera app op [CHAR LIMIT=12]-->
+    <string name="privacy_type_camera">camera</string>
+
+    <!-- Text for location app op [CHAR LIMIT=12]-->
+    <string name="privacy_type_location">location</string>
+
+    <!-- Text for microphone app op [CHAR LIMIT=12]-->
+    <string name="privacy_type_microphone">microphone</string>
 </resources>
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java b/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java
index 8cc6091..8e7fadb 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginInstanceManager.java
@@ -158,6 +158,10 @@
         // If a plugin is detected in the stack of a crash then this will be called for that
         // plugin, if the plugin causing a crash cannot be identified, they are all disabled
         // assuming one of them must be bad.
+        if (mWhitelistedPlugins.contains(info.mPackage)) {
+            // Don't disable whitelisted plugins as they are a part of the OS.
+            return;
+        }
         Log.w(TAG, "Disabling plugin " + info.mPackage + "/" + info.mClass);
         mManager.getPluginEnabler().setEnabled(new ComponentName(info.mPackage, info.mClass),
                 false);
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginManager.java b/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginManager.java
index 208f4fe..3f907a8 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginManager.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginManager.java
@@ -27,6 +27,8 @@
     // must be one of the channels created in NotificationChannels.java
     String NOTIFICATION_CHANNEL_ID = "ALR";
 
+    String[] getWhitelistedPlugins();
+
     <T extends Plugin> T getOneShotPlugin(Class<T> cls);
     <T extends Plugin> T getOneShotPlugin(String action, Class<?> cls);
 
diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java b/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java
index 82e8b3e..dc2a9bd 100644
--- a/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java
+++ b/packages/SystemUI/shared/src/com/android/systemui/shared/plugins/PluginManagerImpl.java
@@ -210,6 +210,10 @@
             Uri uri = intent.getData();
             ComponentName component = ComponentName.unflattenFromString(
                     uri.toString().substring(10));
+            if (mWhitelistedPlugins.contains(component.getPackageName())) {
+                // Don't disable whitelisted plugins as they are a part of the OS.
+                return;
+            }
             getPluginEnabler().setEnabled(component, false);
             mContext.getSystemService(NotificationManager.class).cancel(component.getClassName(),
                     SystemMessage.NOTE_PLUGIN);
diff --git a/packages/SystemUI/src/com/android/systemui/doze/DozeScreenBrightness.java b/packages/SystemUI/src/com/android/systemui/doze/DozeScreenBrightness.java
index c566460..5d99c57 100644
--- a/packages/SystemUI/src/com/android/systemui/doze/DozeScreenBrightness.java
+++ b/packages/SystemUI/src/com/android/systemui/doze/DozeScreenBrightness.java
@@ -141,7 +141,7 @@
     }
 
     private void updateBrightnessAndReady() {
-        if (mRegistered) {
+        if (mRegistered || mDebugBrightnessBucket != -1) {
             int sensorValue = mDebugBrightnessBucket == -1
                     ? mLastSensorValue : mDebugBrightnessBucket;
             int brightness = computeBrightness(sensorValue);
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyChip.kt b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyChip.kt
new file mode 100644
index 0000000..3953139d
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyChip.kt
@@ -0,0 +1,152 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package com.android.systemui.privacy
+
+import android.app.ActivityManager
+import android.app.AppOpsManager
+import android.content.Context
+import android.graphics.Color
+import android.os.UserHandle
+import android.os.UserManager
+import android.util.AttributeSet
+import android.view.ViewGroup
+import android.widget.ImageView
+import android.widget.LinearLayout
+import android.widget.TextView
+import com.android.systemui.Dependency
+import com.android.systemui.R
+import com.android.systemui.appops.AppOpItem
+import com.android.systemui.appops.AppOpsController
+
+class OngoingPrivacyChip @JvmOverloads constructor(
+    context: Context,
+    attrs: AttributeSet? = null,
+    defStyleAttrs: Int = 0,
+    defStyleRes: Int = 0
+) : LinearLayout(context, attrs, defStyleAttrs, defStyleRes) {
+
+    companion object {
+        val OPS = intArrayOf(AppOpsManager.OP_CAMERA,
+                AppOpsManager.OP_RECORD_AUDIO,
+                AppOpsManager.OP_COARSE_LOCATION,
+                AppOpsManager.OP_FINE_LOCATION)
+    }
+
+    private lateinit var appName: TextView
+    private lateinit var iconsContainer: LinearLayout
+    private var privacyList = emptyList<PrivacyItem>()
+    private val appOpsController = Dependency.get(AppOpsController::class.java)
+    private val userManager = context.getSystemService(UserManager::class.java)
+    private val currentUser = ActivityManager.getCurrentUser()
+    private val currentUserIds = userManager.getProfiles(currentUser).map { it.id }
+    private var listening = false
+
+    var builder = PrivacyDialogBuilder(context, privacyList)
+
+    private val callback = object : AppOpsController.Callback {
+        override fun onActiveStateChanged(
+            code: Int,
+            uid: Int,
+            packageName: String,
+            active: Boolean
+        ) {
+            val userId = UserHandle.getUserId(uid)
+            if (userId in currentUserIds) {
+                updatePrivacyList()
+            }
+        }
+    }
+
+    override fun onFinishInflate() {
+        super.onFinishInflate()
+
+        appName = findViewById(R.id.app_name)
+        iconsContainer = findViewById(R.id.icons_container)
+    }
+
+    fun setListening(listen: Boolean) {
+        if (listening == listen) return
+        listening = listen
+        if (listening) {
+            appOpsController.addCallback(OPS, callback)
+            updatePrivacyList()
+        } else {
+            appOpsController.removeCallback(OPS, callback)
+        }
+    }
+
+    private fun updatePrivacyList() {
+        privacyList = currentUserIds.flatMap { appOpsController.getActiveAppOpsForUser(it) }
+                .mapNotNull { toPrivacyItem(it) }
+        builder = PrivacyDialogBuilder(context, privacyList)
+        updateView()
+    }
+
+    private fun toPrivacyItem(appOpItem: AppOpItem): PrivacyItem? {
+        val type: PrivacyType = when (appOpItem.code) {
+            AppOpsManager.OP_CAMERA -> PrivacyType.TYPE_CAMERA
+            AppOpsManager.OP_COARSE_LOCATION -> PrivacyType.TYPE_LOCATION
+            AppOpsManager.OP_FINE_LOCATION -> PrivacyType.TYPE_LOCATION
+            AppOpsManager.OP_RECORD_AUDIO -> PrivacyType.TYPE_MICROPHONE
+            else -> return null
+        }
+        val app = PrivacyApplication(appOpItem.packageName, context)
+        return PrivacyItem(type, app, appOpItem.timeStarted)
+    }
+
+    // Should only be called if the builder icons or app changed
+    private fun updateView() {
+        fun setIcons(dialogBuilder: PrivacyDialogBuilder, iconsContainer: ViewGroup) {
+            iconsContainer.removeAllViews()
+            dialogBuilder.generateIcons().forEach {
+                it.mutate()
+                it.setTint(Color.WHITE)
+                iconsContainer.addView(ImageView(context).apply {
+                    setImageDrawable(it)
+                    maxHeight = this@OngoingPrivacyChip.height
+                })
+            }
+        }
+
+        if (privacyList.isEmpty()) {
+            visibility = GONE
+            return
+        } else {
+            generateContentDescription()
+            visibility = VISIBLE
+            setIcons(builder, iconsContainer)
+            appName.visibility = GONE
+            builder.app?.let {
+                appName.apply {
+                    setText(it.applicationName)
+                    setTextColor(Color.WHITE)
+                    visibility = VISIBLE
+                }
+            }
+        }
+        requestLayout()
+    }
+
+    private fun generateContentDescription() {
+        val typesText = builder.generateTypesText()
+        if (builder.app != null) {
+            contentDescription = context.getString(R.string.ongoing_privacy_chip_content_single_app,
+                    builder.app?.applicationName, typesText)
+        } else {
+            contentDescription = context.getString(
+                    R.string.ongoing_privacy_chip_content_multiple_apps, typesText)
+        }
+    }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
new file mode 100644
index 0000000..1d0e16e
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/privacy/OngoingPrivacyDialog.kt
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package com.android.systemui.privacy
+
+import android.app.AlertDialog
+import android.app.Dialog
+import android.content.Context
+import android.content.DialogInterface
+import android.graphics.drawable.Drawable
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.ImageView
+import android.widget.LinearLayout
+import android.widget.TextView
+import com.android.systemui.Dependency
+import com.android.systemui.R
+import com.android.systemui.plugins.ActivityStarter
+
+class OngoingPrivacyDialog constructor(
+    val context: Context,
+    val dialogBuilder: PrivacyDialogBuilder
+) {
+
+    val iconHeight = context.resources.getDimensionPixelSize(
+            R.dimen.ongoing_appops_dialog_icon_height)
+    val textMargin = context.resources.getDimensionPixelSize(
+            R.dimen.ongoing_appops_dialog_text_margin)
+    val iconColor = context.resources.getColor(
+            com.android.internal.R.color.text_color_primary, context.theme)
+
+    fun createDialog(): Dialog {
+        val builder = AlertDialog.Builder(context)
+                .setNeutralButton(R.string.ongoing_privacy_dialog_open_settings, null)
+        if (dialogBuilder.app != null) {
+            builder.setPositiveButton(R.string.ongoing_privacy_dialog_open_app,
+                    object : DialogInterface.OnClickListener {
+                        val intent = context.packageManager
+                                .getLaunchIntentForPackage(dialogBuilder.app.packageName)
+
+                        override fun onClick(dialog: DialogInterface?, which: Int) {
+                            Dependency.get(ActivityStarter::class.java).startActivity(intent, false)
+                        }
+                    })
+            builder.setNegativeButton(R.string.ongoing_privacy_dialog_cancel, null)
+        } else {
+            builder.setPositiveButton(R.string.ongoing_privacy_dialog_okay, null)
+        }
+        builder.setView(getContentView())
+        return builder.create()
+    }
+
+    fun getContentView(): View {
+        val layoutInflater = LayoutInflater.from(context)
+        val contentView = layoutInflater.inflate(R.layout.ongoing_privacy_dialog_content, null)
+
+        val iconsContainer = contentView.findViewById(R.id.icons_container) as LinearLayout
+        val textContainer = contentView.findViewById(R.id.text_container) as LinearLayout
+
+        addIcons(dialogBuilder, iconsContainer)
+        val lm = ViewGroup.MarginLayoutParams(
+                ViewGroup.MarginLayoutParams.WRAP_CONTENT,
+                ViewGroup.MarginLayoutParams.WRAP_CONTENT)
+        lm.topMargin = textMargin
+        val now = System.currentTimeMillis()
+        dialogBuilder.generateText(now).forEach {
+            val text = layoutInflater.inflate(R.layout.ongoing_privacy_text_item, null) as TextView
+            text.setText(it)
+            textContainer.addView(text, lm)
+        }
+        return contentView
+    }
+
+    private fun addIcons(dialogBuilder: PrivacyDialogBuilder, iconsContainer: LinearLayout) {
+
+        fun LinearLayout.addIcon(icon: Drawable) {
+            val image = ImageView(context).apply {
+                setImageDrawable(icon.apply {
+                    setBounds(0, 0, iconHeight, iconHeight)
+                    maxHeight = this@addIcon.height
+                })
+                adjustViewBounds = true
+            }
+            addView(image, LinearLayout.LayoutParams.WRAP_CONTENT,
+                    LinearLayout.LayoutParams.MATCH_PARENT)
+        }
+
+        dialogBuilder.generateIcons().forEach {
+            it.mutate()
+            it.setTint(iconColor)
+            iconsContainer.addIcon(it)
+        }
+        dialogBuilder.app.let {
+            it?.icon?.let { iconsContainer.addIcon(it) }
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt
new file mode 100644
index 0000000..2f86f78
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogBuilder.kt
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package com.android.systemui.privacy
+
+import android.content.Context
+import com.android.systemui.R
+import java.lang.IllegalStateException
+import java.lang.Math.max
+
+class PrivacyDialogBuilder(val context: Context, itemsList: List<PrivacyItem>) {
+    companion object {
+        val MILLIS_IN_MINUTE: Long = 1000 * 60
+    }
+
+    private val itemsByType: Map<PrivacyType, List<PrivacyItem>>
+    val app: PrivacyApplication?
+
+    init {
+        itemsByType = itemsList.groupBy { it.privacyType }
+        val apps = itemsList.map { it.application }.distinct()
+        val singleApp = apps.size == 1
+        app = if (singleApp) apps.get(0) else null
+    }
+
+    private fun buildTextForItem(type: PrivacyType, now: Long): String {
+        val items = itemsByType.getOrDefault(type, emptyList<PrivacyItem>())
+        return when (items.size) {
+            0 -> throw IllegalStateException("List cannot be empty")
+            1 -> {
+                val item = items.get(0)
+                val minutesUsed = max(((now - item.timeStarted) / MILLIS_IN_MINUTE).toInt(), 1)
+                context.getString(R.string.ongoing_privacy_dialog_app_item,
+                        item.application.applicationName, type.getName(context), minutesUsed)
+            }
+            else -> {
+                val apps = items.map { it.application.applicationName }.joinToString()
+                context.getString(R.string.ongoing_privacy_dialog_apps_item,
+                        apps, type.getName(context))
+            }
+        }
+    }
+
+    private fun buildTextForApp(types: Set<PrivacyType>): List<String> {
+        app?.let {
+            val typesText = types.map { it.getName(context) }.sorted().joinToString()
+            return listOf(context.getString(R.string.ongoing_privacy_dialog_single_app,
+                    it.applicationName, typesText))
+        } ?: throw IllegalStateException("There has to be a single app")
+    }
+
+    fun generateText(now: Long): List<String> {
+        if (app == null || itemsByType.keys.size == 1) {
+            return itemsByType.keys.map { buildTextForItem(it, now) }
+        } else {
+            return buildTextForApp(itemsByType.keys)
+        }
+    }
+
+    fun generateTypesText() = itemsByType.keys.map { it.getName(context) }.sorted().joinToString()
+
+    fun generateIcons() = itemsByType.keys.map { it.getIcon(context) }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt
new file mode 100644
index 0000000..f409902
--- /dev/null
+++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyItem.kt
@@ -0,0 +1,55 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
+ * except in compliance with the License. You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software distributed under the
+ * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the specific language governing
+ * permissions and limitations under the License.
+ */
+
+package com.android.systemui.privacy
+
+import android.content.Context
+import android.content.pm.ApplicationInfo
+import android.content.pm.PackageManager
+import android.graphics.drawable.Drawable
+import com.android.systemui.R
+
+typealias Privacy = PrivacyType
+
+enum class PrivacyType(val nameId: Int, val iconId: Int) {
+    TYPE_CAMERA(R.string.privacy_type_camera, com.android.internal.R.drawable.ic_camera),
+    TYPE_LOCATION(R.string.privacy_type_location, R.drawable.stat_sys_location),
+    TYPE_MICROPHONE(R.string.privacy_type_microphone, R.drawable.ic_mic_26dp);
+
+    fun getName(context: Context) = context.resources.getString(nameId)
+
+    fun getIcon(context: Context) = context.resources.getDrawable(iconId, null)
+}
+
+data class PrivacyItem(
+    val privacyType: PrivacyType,
+    val application: PrivacyApplication,
+    val timeStarted: Long
+)
+
+data class PrivacyApplication(val packageName: String, val context: Context) {
+    var icon: Drawable? = null
+    var applicationName: String
+
+    init {
+        try {
+            val app: ApplicationInfo = context.packageManager
+                    .getApplicationInfo(packageName, 0)
+            icon = context.packageManager.getApplicationIcon(app)
+            applicationName = context.packageManager.getApplicationLabel(app) as String
+        } catch (e: PackageManager.NameNotFoundException) {
+            applicationName = packageName
+        }
+    }
+}
diff --git a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
index 326df49..3ee6195 100644
--- a/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
+++ b/packages/SystemUI/src/com/android/systemui/qs/QuickStatusBarHeader.java
@@ -21,6 +21,7 @@
 import android.annotation.ColorInt;
 import android.app.ActivityManager;
 import android.app.AlarmManager;
+import android.app.Dialog;
 import android.content.BroadcastReceiver;
 import android.content.Context;
 import android.content.Intent;
@@ -31,6 +32,7 @@
 import android.graphics.Rect;
 import android.media.AudioManager;
 import android.os.Handler;
+import android.os.Looper;
 import android.provider.AlarmClock;
 import android.service.notification.ZenModeConfig;
 import android.text.format.DateUtils;
@@ -39,6 +41,7 @@
 import android.util.Pair;
 import android.view.View;
 import android.view.WindowInsets;
+import android.view.WindowManager;
 import android.widget.FrameLayout;
 import android.widget.ImageView;
 import android.widget.RelativeLayout;
@@ -52,11 +55,14 @@
 import com.android.systemui.Prefs;
 import com.android.systemui.R;
 import com.android.systemui.plugins.ActivityStarter;
+import com.android.systemui.privacy.OngoingPrivacyChip;
+import com.android.systemui.privacy.OngoingPrivacyDialog;
 import com.android.systemui.qs.QSDetail.Callback;
 import com.android.systemui.statusbar.phone.PhoneStatusBarView;
 import com.android.systemui.statusbar.phone.StatusBarIconController;
 import com.android.systemui.statusbar.phone.StatusBarIconController.TintedIconManager;
 import com.android.systemui.statusbar.phone.StatusIconContainer;
+import com.android.systemui.statusbar.phone.SystemUIDialog;
 import com.android.systemui.statusbar.policy.Clock;
 import com.android.systemui.statusbar.policy.DarkIconDispatcher;
 import com.android.systemui.statusbar.policy.DarkIconDispatcher.DarkReceiver;
@@ -118,6 +124,7 @@
     private BatteryMeterView mBatteryMeterView;
     private Clock mClockView;
     private DateView mDateView;
+    private OngoingPrivacyChip mPrivacyChip;
 
     private NextAlarmController mAlarmController;
     private ZenModeController mZenController;
@@ -185,6 +192,8 @@
         mClockView = findViewById(R.id.clock);
         mClockView.setOnClickListener(this);
         mDateView = findViewById(R.id.date);
+        mPrivacyChip = findViewById(R.id.privacy_chip);
+        mPrivacyChip.setOnClickListener(this);
     }
 
     private void updateStatusText() {
@@ -263,6 +272,13 @@
                 newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;
         mBatteryMeterView.useWallpaperTextColor(shouldUseWallpaperTextColor);
         mClockView.useWallpaperTextColor(shouldUseWallpaperTextColor);
+
+        MarginLayoutParams lm = (MarginLayoutParams) mPrivacyChip.getLayoutParams();
+        int sideMargins = lm.leftMargin;
+        int topBottomMargins = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
+                ? 0 : sideMargins;
+        lm.setMargins(sideMargins, topBottomMargins, sideMargins, topBottomMargins);
+        mPrivacyChip.setLayoutParams(lm);
     }
 
     @Override
@@ -421,6 +437,7 @@
             return;
         }
         mHeaderQsPanel.setListening(listening);
+        mPrivacyChip.setListening(listening);
         mListening = listening;
 
         if (listening) {
@@ -443,6 +460,19 @@
         } else if (v == mBatteryMeterView) {
             Dependency.get(ActivityStarter.class).postStartActivityDismissingKeyguard(new Intent(
                     Intent.ACTION_POWER_USAGE_SUMMARY),0);
+        } else if (v == mPrivacyChip) {
+            Handler mUiHandler = new Handler(Looper.getMainLooper());
+            mUiHandler.post(() -> {
+                Dialog mDialog = new OngoingPrivacyDialog(mContext,
+                        mPrivacyChip.getBuilder()).createDialog();
+                mDialog.getWindow().setType(
+                        WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
+                SystemUIDialog.setShowForAllUsers(mDialog, true);
+                SystemUIDialog.registerDismissListener(mDialog);
+                SystemUIDialog.setWindowOnTop(mDialog);
+                mUiHandler.post(() -> mDialog.show());
+                mHost.collapsePanels();
+            });
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java
index bc662e3..8994568 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManager.java
@@ -15,6 +15,7 @@
 package com.android.systemui.statusbar;
 
 import android.content.pm.UserInfo;
+import android.os.SystemProperties;
 import android.service.notification.StatusBarNotification;
 import android.util.SparseArray;
 
@@ -25,6 +26,8 @@
     String NOTIFICATION_UNLOCKED_BY_WORK_CHALLENGE_ACTION
             = "com.android.systemui.statusbar.work_challenge_unlocked_notification_action";
 
+    boolean AUTO_DEMOTE_NOTIFICATIONS = SystemProperties.getBoolean("debug.demote_notifs", false);
+
     boolean shouldAllowLockscreenRemoteInput();
 
     /**
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
index 427d169..0108469 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/NotificationLockscreenUserManagerImpl.java
@@ -292,9 +292,16 @@
             Log.wtf(TAG, "mEntryManager was null!", new Throwable());
             return false;
         }
-        return mShowLockscreenNotifications
-                && getEntryManager().getNotificationData().getImportance(sbn.getKey())
-                >= IMPORTANCE_DEFAULT;
+        boolean exceedsPriorityThreshold;
+        if (AUTO_DEMOTE_NOTIFICATIONS) {
+            exceedsPriorityThreshold =
+                    getEntryManager().getNotificationData().getImportance(sbn.getKey())
+                            >= IMPORTANCE_DEFAULT;
+        } else {
+            exceedsPriorityThreshold =
+                    !getEntryManager().getNotificationData().isAmbient(sbn.getKey());
+        }
+        return mShowLockscreenNotifications && exceedsPriorityThreshold;
     }
 
     private void setShowLockscreenNotifications(boolean show) {
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java
index 4918825..f50e9a2 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationIconAreaController.java
@@ -20,6 +20,7 @@
 import com.android.internal.widget.ViewClippingUtil;
 import com.android.systemui.Dependency;
 import com.android.systemui.R;
+import com.android.systemui.statusbar.NotificationLockscreenUserManager;
 import com.android.systemui.statusbar.NotificationShelf;
 import com.android.systemui.statusbar.StatusBarIconView;
 import com.android.systemui.statusbar.notification.NotificationData;
@@ -48,7 +49,8 @@
         @Override
         public void onTuningChanged(String key, String newValue) {
             if (key.equals(LOW_PRIORITY)) {
-                mShowLowPriority = "1".equals(newValue);
+                mShowLowPriority = "1".equals(newValue)
+                        || !NotificationLockscreenUserManager.AUTO_DEMOTE_NOTIFICATIONS;
                 if (mNotificationScrollLayout != null) {
                     updateStatusBarIcons();
                 }
@@ -234,7 +236,8 @@
 
     public void updateStatusBarIcons() {
         updateIconsForLayout(entry -> entry.icon, mNotificationIcons,
-                false /* showAmbient */, false /* showLowPriority */, true /* hideDismissed */,
+                false /* showAmbient */, mShowLowPriority /* showLowPriority */,
+                true /* hideDismissed */,
                 true /* hideRepliedMessages */);
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarSignalPolicy.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarSignalPolicy.java
index 4c24a21..f81ffe9 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarSignalPolicy.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarSignalPolicy.java
@@ -38,6 +38,7 @@
 import com.android.systemui.statusbar.policy.NetworkController.IconState;
 import com.android.systemui.statusbar.policy.NetworkControllerImpl;
 import com.android.systemui.statusbar.policy.SecurityController;
+import com.android.systemui.tuner.TunerService;
 import com.android.systemui.tuner.TunerService.Tunable;
 import java.util.ArrayList;
 import java.util.List;
@@ -88,11 +89,13 @@
         mNetworkController = Dependency.get(NetworkController.class);
         mSecurityController = Dependency.get(SecurityController.class);
 
+        Dependency.get(TunerService.class).addTunable(this, StatusBarIconController.ICON_BLACKLIST);
         mNetworkController.addCallback(this);
         mSecurityController.addCallback(this);
     }
 
     public void destroy() {
+        Dependency.get(TunerService.class).removeTunable(this);
         mNetworkController.removeCallback(this);
         mSecurityController.removeCallback(this);
     }
@@ -137,6 +140,7 @@
             mBlockWifi = blockWifi || mForceBlockWifi;
             // Re-register to get new callbacks.
             mNetworkController.removeCallback(this);
+            mNetworkController.addCallback(this);
         }
     }
 
diff --git a/packages/SystemUI/src/com/android/systemui/tuner/PluginFragment.java b/packages/SystemUI/src/com/android/systemui/tuner/PluginFragment.java
index 0826054..ecb830c 100644
--- a/packages/SystemUI/src/com/android/systemui/tuner/PluginFragment.java
+++ b/packages/SystemUI/src/com/android/systemui/tuner/PluginFragment.java
@@ -29,6 +29,8 @@
 import android.util.ArraySet;
 import android.view.View;
 
+import com.android.internal.util.ArrayUtils;
+import com.android.systemui.Dependency;
 import com.android.systemui.R;
 import com.android.systemui.plugins.PluginEnablerImpl;
 import com.android.systemui.shared.plugins.PluginEnabler;
@@ -77,6 +79,7 @@
     }
 
     private void loadPrefs() {
+        PluginManager manager = Dependency.get(PluginManager.class);
         PreferenceScreen screen = getPreferenceManager().createPreferenceScreen(getContext());
         screen.setOrderingAsAdded(false);
         Context prefContext = getPreferenceManager().getContext();
@@ -103,6 +106,10 @@
                 PackageManager.MATCH_DISABLED_COMPONENTS | PackageManager.GET_SERVICES);
         apps.forEach(app -> {
             if (!plugins.containsKey(app.packageName)) return;
+            if (ArrayUtils.contains(manager.getWhitelistedPlugins(), app.packageName)) {
+                // Don't manage whitelisted plugins, they are part of the OS.
+                return;
+            }
             SwitchPreference pref = new PluginPreference(prefContext, app, mPluginEnabler);
             pref.setSummary("Plugins: " + toString(plugins.get(app.packageName)));
             screen.addPreference(pref);
diff --git a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt
new file mode 100644
index 0000000..7204d31
--- /dev/null
+++ b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogBuilderTest.kt
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.systemui.privacy
+
+import android.support.test.filters.SmallTest
+import android.support.test.runner.AndroidJUnit4
+import com.android.systemui.SysuiTestCase
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import org.junit.runner.RunWith
+
+@RunWith(AndroidJUnit4::class)
+@SmallTest
+class PrivacyDialogBuilderTest : SysuiTestCase() {
+
+    companion object {
+        val MILLIS_IN_MINUTE: Long = 1000 * 60
+        val NOW = 4 * MILLIS_IN_MINUTE
+    }
+
+    @Test
+    fun testGenerateText_multipleApps() {
+        val bar2 = PrivacyItem(Privacy.TYPE_CAMERA, PrivacyApplication(
+                "Bar", context), 2 * MILLIS_IN_MINUTE)
+        val bar3 = PrivacyItem(Privacy.TYPE_LOCATION, PrivacyApplication(
+                "Bar", context), 3 * MILLIS_IN_MINUTE)
+        val foo0 = PrivacyItem(Privacy.TYPE_CAMERA, PrivacyApplication(
+                "Foo", context), 0)
+        val baz1 = PrivacyItem(Privacy.TYPE_CAMERA, PrivacyApplication(
+                "Baz", context), 1 * MILLIS_IN_MINUTE)
+
+        val items = listOf(bar2, foo0, baz1, bar3)
+
+        val textBuilder = PrivacyDialogBuilder(context, items)
+
+        val textList = textBuilder.generateText(NOW)
+        assertEquals(2, textList.size)
+        assertEquals("Bar, Foo, Baz are using your camera", textList[0])
+        assertEquals("Bar is using your location for the last 1 min", textList[1])
+    }
+
+    @Test
+    fun testGenerateText_singleApp() {
+        val bar2 = PrivacyItem(Privacy.TYPE_CAMERA, PrivacyApplication(
+                "Bar", context), 0)
+        val bar1 = PrivacyItem(Privacy.TYPE_LOCATION, PrivacyApplication(
+                "Bar", context), 0)
+
+        val items = listOf(bar2, bar1)
+
+        val textBuilder = PrivacyDialogBuilder(context, items)
+        val textList = textBuilder.generateText(NOW)
+        assertEquals(1, textList.size)
+        assertEquals("Bar is using your camera, location", textList[0])
+    }
+
+    @Test
+    fun testGenerateText_singleApp_singleType() {
+        val bar2 = PrivacyItem(Privacy.TYPE_CAMERA, PrivacyApplication(
+                "Bar", context), 2 * MILLIS_IN_MINUTE)
+        val items = listOf(bar2)
+        val textBuilder = PrivacyDialogBuilder(context, items)
+        val textList = textBuilder.generateText(NOW)
+        assertEquals(1, textList.size)
+        assertEquals("Bar is using your camera for the last 2 min", textList[0])
+    }
+}
\ No newline at end of file
diff --git a/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/PluginInstanceManagerTest.java b/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/PluginInstanceManagerTest.java
index 5bf6040..5cc3b3c 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/PluginInstanceManagerTest.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/shared/plugins/PluginInstanceManagerTest.java
@@ -22,6 +22,7 @@
 import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.doThrow;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
@@ -122,7 +123,7 @@
         waitForIdleSync(mPluginInstanceManager.mPluginHandler);
         waitForIdleSync(mPluginInstanceManager.mMainHandler);
 
-        verify(mMockListener, Mockito.never()).onPluginConnected(any(), any());
+        verify(mMockListener, never()).onPluginConnected(any(), any());
     }
 
     @Test
@@ -162,7 +163,7 @@
         waitForIdleSync(mPluginInstanceManager.mMainHandler);
 
         // Plugin shouldn't be connected because it is the wrong version.
-        verify(mMockListener, Mockito.never()).onPluginConnected(any(), any());
+        verify(mMockListener, never()).onPluginConnected(any(), any());
         verify(nm).notifyAsUser(eq(TestPlugin.class.getName()), eq(SystemMessage.NOTE_PLUGIN),
                 any(), eq(UserHandle.ALL));
     }
@@ -200,7 +201,7 @@
         waitForIdleSync(mPluginInstanceManager.mMainHandler);;
 
         // Non-debuggable build should receive no plugins.
-        verify(mMockListener, Mockito.never()).onPluginConnected(any(), any());
+        verify(mMockListener, never()).onPluginConnected(any(), any());
     }
 
     @Test
@@ -229,7 +230,7 @@
         // Start with an unrelated class.
         boolean result = mPluginInstanceManager.checkAndDisable(Activity.class.getName());
         assertFalse(result);
-        verify(mMockPm, Mockito.never()).setComponentEnabledSetting(
+        verify(mMockPm, never()).setComponentEnabledSetting(
                 ArgumentCaptor.forClass(ComponentName.class).capture(),
                 ArgumentCaptor.forClass(int.class).capture(),
                 ArgumentCaptor.forClass(int.class).capture());
@@ -255,6 +256,21 @@
                 ArgumentCaptor.forClass(int.class).capture());
     }
 
+    @Test
+    public void testDisableWhitelisted() throws Exception {
+        mPluginInstanceManager = new PluginInstanceManager(mContextWrapper, mMockPm, "myAction",
+                mMockListener, true, mHandlerThread.getLooper(), mMockVersionInfo,
+                mMockManager, false, new String[] {WHITELISTED_PACKAGE});
+        createPlugin(); // Get into valid created state.
+
+        mPluginInstanceManager.disableAll();
+
+        verify(mMockPm, never()).setComponentEnabledSetting(
+                ArgumentCaptor.forClass(ComponentName.class).capture(),
+                ArgumentCaptor.forClass(int.class).capture(),
+                ArgumentCaptor.forClass(int.class).capture());
+    }
+
     private void setupFakePmQuery() throws Exception {
         List<ResolveInfo> list = new ArrayList<>();
         ResolveInfo info = new ResolveInfo();
diff --git a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakePluginManager.java b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakePluginManager.java
index 5f54bce..6d1e6ce 100644
--- a/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakePluginManager.java
+++ b/packages/SystemUI/tests/src/com/android/systemui/utils/leaks/FakePluginManager.java
@@ -62,6 +62,11 @@
     }
 
     @Override
+    public String[] getWhitelistedPlugins() {
+        return new String[0];
+    }
+
+    @Override
     public <T extends Plugin> T getOneShotPlugin(Class<T> cls) {
         return null;
     }
diff --git a/services/art-profile b/services/art-profile
index 742ca1c..bdd49de 100644
--- a/services/art-profile
+++ b/services/art-profile
@@ -2271,6 +2271,7 @@
 HPLcom/android/server/wm/DisplayContent;->prepareSurfaces()V
 HPLcom/android/server/wm/DisplayContent;->resetAnimationBackgroundAnimator()V
 HPLcom/android/server/wm/DisplayContent;->skipTraverseChild(Lcom/android/server/wm/WindowContainer;)Z
+HPLcom/android/server/wm/DisplayContent;->updateOrientationFromAppTokens(Z)Z
 HPLcom/android/server/wm/DisplayContent;->updateTouchExcludeRegion()V
 HPLcom/android/server/wm/DockedStackDividerController;->isResizing()Z
 HPLcom/android/server/wm/DragDropController;->dragDropActiveLocked()Z
@@ -2451,7 +2452,6 @@
 HPLcom/android/server/wm/WindowManagerService;->resetPriorityAfterLockedSection()V
 HPLcom/android/server/wm/WindowManagerService;->scheduleAnimationLocked()V
 HPLcom/android/server/wm/WindowManagerService;->traceStateLocked(Ljava/lang/String;)V
-HPLcom/android/server/wm/WindowManagerService;->updateOrientationFromAppTokensLocked(IZ)Z
 HPLcom/android/server/wm/WindowManagerService;->windowForClientLocked(Lcom/android/server/wm/Session;Landroid/os/IBinder;Z)Lcom/android/server/wm/WindowState;
 HPLcom/android/server/wm/WindowManagerThreadPriorityBooster;->boost()V
 HPLcom/android/server/wm/WindowManagerThreadPriorityBooster;->reset()V
@@ -18137,6 +18137,7 @@
 PLcom/android/server/wm/DisplayContent;->updateBounds()V
 PLcom/android/server/wm/DisplayContent;->updateDisplayAndOrientation(I)Landroid/view/DisplayInfo;
 PLcom/android/server/wm/DisplayContent;->updateDisplayInfo()V
+PLcom/android/server/wm/DisplayContent;->updateOrientationFromAppTokens()Z
 PLcom/android/server/wm/DisplayContent;->updateRotationUnchecked()Z
 PLcom/android/server/wm/DisplayContent;->updateRotationUnchecked(Z)Z
 PLcom/android/server/wm/DisplayContent;->updateStackBoundsAfterConfigChange(Ljava/util/List;)V
@@ -18906,7 +18907,6 @@
 PLcom/android/server/wm/WindowManagerService;->updateNonSystemOverlayWindowsVisibilityIfNeeded(Lcom/android/server/wm/WindowState;Z)V
 PLcom/android/server/wm/WindowManagerService;->updateOrientationFromAppTokens(Landroid/content/res/Configuration;Landroid/os/IBinder;I)Landroid/content/res/Configuration;
 PLcom/android/server/wm/WindowManagerService;->updateOrientationFromAppTokens(Landroid/content/res/Configuration;Landroid/os/IBinder;IZ)Landroid/content/res/Configuration;
-PLcom/android/server/wm/WindowManagerService;->updateOrientationFromAppTokensLocked(I)Z
 PLcom/android/server/wm/WindowManagerService;->updateOrientationFromAppTokensLocked(Landroid/content/res/Configuration;Landroid/os/IBinder;IZ)Landroid/content/res/Configuration;
 PLcom/android/server/wm/WindowManagerService;->updatePointerIcon(Landroid/view/IWindow;)V
 PLcom/android/server/wm/WindowManagerService;->updateRotation(ZZ)V
diff --git a/services/core/Android.bp b/services/core/Android.bp
index 2fa2941..888ad1d 100644
--- a/services/core/Android.bp
+++ b/services/core/Android.bp
@@ -55,7 +55,7 @@
     srcs: [":services.core.unboosted"],
     tools: ["lockedregioncodeinjection"],
     cmd: "$(location lockedregioncodeinjection) " +
-        "  --targets \"Lcom/android/server/am/ActivityManagerService;,Lcom/android/server/wm/WindowHashMap;\" " +
+        "  --targets \"Lcom/android/server/am/ActivityManagerService;,Lcom/android/server/wm/WindowManagerGlobalLock;\" " +
         "  --pre \"com/android/server/am/ActivityManagerService.boostPriorityForLockedSection,com/android/server/wm/WindowManagerService.boostPriorityForLockedSection\" " +
         "  --post \"com/android/server/am/ActivityManagerService.resetPriorityAfterLockedSection,com/android/server/wm/WindowManagerService.resetPriorityAfterLockedSection\" " +
         "  -o $(out) " +
diff --git a/services/core/java/com/android/server/AlarmManagerService.java b/services/core/java/com/android/server/AlarmManagerService.java
index 38b9647..854c03f 100644
--- a/services/core/java/com/android/server/AlarmManagerService.java
+++ b/services/core/java/com/android/server/AlarmManagerService.java
@@ -1462,6 +1462,10 @@
         TimeZone.setDefault(null);
 
         if (timeZoneWasChanged) {
+            // Don't wait for broadcasts to update our midnight alarm
+            mClockReceiver.scheduleDateChangedEvent();
+
+            // And now let everyone else know
             Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
             intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
                     | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
diff --git a/services/core/java/com/android/server/AppOpsService.java b/services/core/java/com/android/server/AppOpsService.java
index c2aec29..cd98263 100644
--- a/services/core/java/com/android/server/AppOpsService.java
+++ b/services/core/java/com/android/server/AppOpsService.java
@@ -26,10 +26,14 @@
 import static android.app.AppOpsManager._NUM_UID_STATE;
 
 import android.Manifest;
+import android.annotation.NonNull;
+import android.annotation.Nullable;
 import android.app.ActivityManager;
 import android.app.ActivityThread;
 import android.app.AppGlobals;
 import android.app.AppOpsManager;
+import android.app.AppOpsManager.HistoricalOpEntry;
+import android.app.AppOpsManager.HistoricalPackageOps;
 import android.app.AppOpsManagerInternal;
 import android.app.AppOpsManagerInternal.CheckOpsDelegate;
 import android.content.ContentResolver;
@@ -38,6 +42,7 @@
 import android.content.pm.IPackageManager;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManagerInternal;
+import android.content.pm.ParceledListSlice;
 import android.content.pm.UserInfo;
 import android.database.ContentObserver;
 import android.media.AudioAttributes;
@@ -929,6 +934,116 @@
     }
 
     @Override
+    public @Nullable ParceledListSlice getAllHistoricalPackagesOps(@Nullable String[] opNames,
+            long beginTimeMillis, long endTimeMillis) {
+        Preconditions.checkArgument(beginTimeMillis >= 0 && beginTimeMillis < endTimeMillis,
+                "beginTimeMillis must be non negative and lesser than endTimeMillis");
+
+        mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
+                Binder.getCallingPid(), Binder.getCallingUid(), "getAllHistoricalPackagesOps");
+
+        ArrayList<HistoricalPackageOps> historicalPackageOpsList = null;
+
+        final int uidStateCount = mUidStates.size();
+        for (int i = 0; i < uidStateCount; i++) {
+            final UidState uidState = mUidStates.valueAt(i);
+            if (uidState.pkgOps == null || uidState.pkgOps.isEmpty()) {
+                continue;
+            }
+            final ArrayMap<String, Ops> packages = uidState.pkgOps;
+            final int packageCount = packages.size();
+            for (int j = 0; j < packageCount; j++) {
+                final Ops pkgOps = packages.valueAt(j);
+                final AppOpsManager.HistoricalPackageOps historicalPackageOps =
+                        createHistoricalPackageOps(uidState.uid, pkgOps, opNames,
+                                beginTimeMillis, endTimeMillis);
+                if (historicalPackageOps != null) {
+                    if (historicalPackageOpsList == null) {
+                        historicalPackageOpsList = new ArrayList<>();
+                    }
+                    historicalPackageOpsList.add(historicalPackageOps);
+                }
+            }
+        }
+
+        if (historicalPackageOpsList == null) {
+            return null;
+        }
+
+        return new ParceledListSlice<>(historicalPackageOpsList);
+    }
+
+    private static @Nullable HistoricalPackageOps createHistoricalPackageOps(int uid,
+            @Nullable Ops pkgOps, @Nullable String[] opNames, long beginTimeMillis,
+            long endTimeMillis) {
+        // TODO: Implement historical data collection
+        if (pkgOps == null) {
+            return null;
+        }
+
+        final HistoricalPackageOps historicalPackageOps = new HistoricalPackageOps(uid,
+                pkgOps.packageName);
+
+        if (opNames == null) {
+            opNames = AppOpsManager.getOpStrs();
+        }
+        for (String opName : opNames) {
+            addHistoricOpEntry(AppOpsManager.strOpToOp(opName), pkgOps, historicalPackageOps);
+        }
+
+        return historicalPackageOps;
+    }
+
+    @Override
+    public @Nullable HistoricalPackageOps getHistoricalPackagesOps(int uid,
+            @NonNull String packageName, @Nullable String[] opNames,
+            long beginTimeMillis, long endTimeMillis) {
+        Preconditions.checkNotNull(packageName,
+                "packageName cannot be null");
+        Preconditions.checkArgument(beginTimeMillis >= 0 && beginTimeMillis < endTimeMillis,
+                "beginTimeMillis must be non negative and lesser than endTimeMillis");
+
+        mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
+                Binder.getCallingPid(), Binder.getCallingUid(), "getHistoricalPackagesOps");
+
+        final String resolvedPackageName = resolvePackageName(uid, packageName);
+        if (resolvedPackageName == null) {
+            return null;
+        }
+
+        // TODO: Implement historical data collection
+        final Ops pkgOps = getOpsRawLocked(uid, resolvedPackageName, false /* edit */,
+                false /* uidMismatchExpected */);
+        return createHistoricalPackageOps(uid, pkgOps, opNames, beginTimeMillis, endTimeMillis);
+    }
+
+    private static void addHistoricOpEntry(int opCode, @NonNull Ops ops,
+            @NonNull HistoricalPackageOps outHistoricalPackageOps) {
+        final Op op = ops.get(opCode);
+        if (op == null) {
+            return;
+        }
+
+        final HistoricalOpEntry historicalOpEntry = new HistoricalOpEntry(opCode);
+
+        // TODO: Keep per UID state duration
+        for (int uidState = 0; uidState < AppOpsManager._NUM_UID_STATE; uidState++) {
+            final int acceptCount;
+            final int rejectCount;
+            if (op.rejectTime[uidState] == 0) {
+                acceptCount = 1;
+                rejectCount = 0;
+            } else {
+                acceptCount = 0;
+                rejectCount = 1;
+            }
+            historicalOpEntry.addEntry(uidState, acceptCount, rejectCount, 0);
+        }
+
+        outHistoricalPackageOps.addEntry(historicalOpEntry);
+    }
+
+    @Override
     public List<AppOpsManager.PackageOps> getUidOps(int uid, int[] ops) {
         mContext.enforcePermission(android.Manifest.permission.GET_APP_OPS_STATS,
                 Binder.getCallingPid(), Binder.getCallingUid(), null);
@@ -2020,7 +2135,8 @@
                     try {
                         ApplicationInfo appInfo = ActivityThread.getPackageManager()
                                 .getApplicationInfo(packageName,
-                                        PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
+                                        PackageManager.MATCH_DIRECT_BOOT_AWARE
+                                        | PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
                                         UserHandle.getUserId(uid));
                         if (appInfo != null) {
                             pkgUid = appInfo.uid;
diff --git a/services/core/java/com/android/server/am/ActiveServices.java b/services/core/java/com/android/server/am/ActiveServices.java
index 405a2d0..2d3912b 100644
--- a/services/core/java/com/android/server/am/ActiveServices.java
+++ b/services/core/java/com/android/server/am/ActiveServices.java
@@ -95,6 +95,7 @@
 import android.util.proto.ProtoOutputStream;
 import android.webkit.WebViewZygote;
 import com.android.server.uri.NeededUriGrants;
+import com.android.server.wm.ActivityServiceConnectionsHolder;
 
 public final class ActiveServices {
     private static final String TAG = TAG_WITH_CLASS_NAME ? "ActiveServices" : TAG_AM;
diff --git a/services/core/java/com/android/server/am/ActivityManagerService.java b/services/core/java/com/android/server/am/ActivityManagerService.java
index b06320a..d631fa8 100644
--- a/services/core/java/com/android/server/am/ActivityManagerService.java
+++ b/services/core/java/com/android/server/am/ActivityManagerService.java
@@ -127,23 +127,23 @@
 import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_UID_OBSERVERS;
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
-import static com.android.server.am.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD;
-import static com.android.server.am.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD;
-import static com.android.server.am.ActivityTaskManagerService.DUMP_CONTAINERS_CMD;
-import static com.android.server.am.ActivityTaskManagerService.DUMP_LASTANR_CMD;
-import static com.android.server.am.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD;
-import static com.android.server.am.ActivityTaskManagerService.DUMP_RECENTS_CMD;
-import static com.android.server.am.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD;
-import static com.android.server.am.ActivityTaskManagerService.DUMP_STARTER_CMD;
-import static com.android.server.am.ActivityTaskManagerService.KEY_DISPATCHING_TIMEOUT_MS;
-import static com.android.server.am.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
-import static com.android.server.am.ActivityTaskManagerService.relaunchReasonToString;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
+import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_CMD;
+import static com.android.server.wm.ActivityTaskManagerService.DUMP_ACTIVITIES_SHORT_CMD;
+import static com.android.server.wm.ActivityTaskManagerService.DUMP_CONTAINERS_CMD;
+import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_CMD;
+import static com.android.server.wm.ActivityTaskManagerService.DUMP_LASTANR_TRACES_CMD;
+import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_CMD;
+import static com.android.server.wm.ActivityTaskManagerService.DUMP_RECENTS_SHORT_CMD;
+import static com.android.server.wm.ActivityTaskManagerService.DUMP_STARTER_CMD;
+import static com.android.server.wm.ActivityTaskManagerService.KEY_DISPATCHING_TIMEOUT_MS;
+import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
+import static com.android.server.wm.ActivityTaskManagerService.relaunchReasonToString;
 import static com.android.server.am.MemoryStatUtil.MEMORY_STAT_INTERESTING_NATIVE_PROCESSES;
 import static com.android.server.am.MemoryStatUtil.hasMemcg;
 import static com.android.server.am.MemoryStatUtil.readCmdlineFromProcfs;
@@ -352,8 +352,11 @@
 import com.android.server.uri.UriGrantsManagerInternal;
 import com.android.server.utils.PriorityDump;
 import com.android.server.vr.VrManagerInternal;
+import com.android.server.wm.ActivityServiceConnectionsHolder;
 import com.android.server.wm.ActivityTaskManagerInternal;
+import com.android.server.wm.ActivityTaskManagerService;
 import com.android.server.wm.WindowManagerService;
+import com.android.server.wm.WindowProcessController;
 
 import dalvik.system.VMRuntime;
 
@@ -567,7 +570,8 @@
     String mDeviceOwnerName;
 
     final UserController mUserController;
-    final PendingIntentController mPendingIntentController;
+    @VisibleForTesting
+    public final PendingIntentController mPendingIntentController;
 
     final AppErrors mAppErrors;
 
@@ -1276,10 +1280,14 @@
      */
     int mBootPhase;
 
-    WindowManagerService mWindowManager;
-    ActivityTaskManagerService mActivityTaskManager;
-    ActivityTaskManagerInternal mAtmInternal;
-    UriGrantsManagerInternal mUgmInternal;
+    @VisibleForTesting
+    public WindowManagerService mWindowManager;
+    @VisibleForTesting
+    public ActivityTaskManagerService mActivityTaskManager;
+    @VisibleForTesting
+    public ActivityTaskManagerInternal mAtmInternal;
+    @VisibleForTesting
+    public UriGrantsManagerInternal mUgmInternal;
     final ActivityThread mSystemThread;
 
     private final class AppDeathRecipient implements IBinder.DeathRecipient {
@@ -1349,7 +1357,8 @@
      */
     private boolean mUserIsMonkey;
 
-    final ServiceThread mHandlerThread;
+    @VisibleForTesting
+    public final ServiceThread mHandlerThread;
     final MainHandler mHandler;
     final Handler mUiHandler;
     final ServiceThread mProcStartHandlerThread;
@@ -2111,7 +2120,7 @@
      * given to initialize the dependency members.
      */
     @VisibleForTesting
-    ActivityManagerService(Injector injector, ServiceThread handlerThread) {
+    public ActivityManagerService(Injector injector, ServiceThread handlerThread) {
         final boolean hasHandlerThread = handlerThread != null;
         mInjector = injector;
         mContext = mInjector.getContext();
@@ -5556,7 +5565,8 @@
         return pi;
     }
 
-    void grantEphemeralAccessLocked(int userId, Intent intent,
+    @VisibleForTesting
+    public void grantEphemeralAccessLocked(int userId, Intent intent,
             int targetAppId, int ephemeralAppId) {
         getPackageManagerInternalLocked().
                 grantEphemeralAccess(userId, intent, targetAppId, ephemeralAppId);
@@ -6509,6 +6519,7 @@
 
         // Wait for the provider to be published...
         final long timeout = SystemClock.uptimeMillis() + CONTENT_PROVIDER_WAIT_TIMEOUT;
+        boolean timedOut = false;
         synchronized (cpr) {
             while (cpr.provider == null) {
                 if (cpr.launchingApp == null) {
@@ -6532,12 +6543,8 @@
                     }
                     cpr.wait(wait);
                     if (cpr.provider == null) {
-                        Slog.wtf(TAG, "Timeout waiting for provider "
-                                + cpi.applicationInfo.packageName + "/"
-                                + cpi.applicationInfo.uid + " for provider "
-                                + name
-                                + " providerRunning=" + providerRunning);
-                        return null;
+                        timedOut = true;
+                        break;
                     }
                 } catch (InterruptedException ex) {
                 } finally {
@@ -6547,7 +6554,26 @@
                 }
             }
         }
-        return cpr != null ? cpr.newHolder(conn) : null;
+        if (timedOut) {
+            // Note we do it afer releasing the lock.
+            String callerName = "unknown";
+            synchronized (this) {
+                final ProcessRecord record = mProcessList.getLRURecordForAppLocked(caller);
+                if (record != null) {
+                    callerName = record.processName;
+                }
+            }
+
+            Slog.wtf(TAG, "Timeout waiting for provider "
+                    + cpi.applicationInfo.packageName + "/"
+                    + cpi.applicationInfo.uid + " for provider "
+                    + name
+                    + " providerRunning=" + providerRunning
+                    + " caller=" + callerName + "/" + Binder.getCallingUid());
+            return null;
+        }
+
+        return cpr.newHolder(conn);
     }
 
     private static final class StartActivityRunnable implements Runnable {
@@ -6606,11 +6632,13 @@
      * PackageManager could be unavailable at construction time and therefore needs to be accessed
      * on demand.
      */
-    IPackageManager getPackageManager() {
+    @VisibleForTesting
+    public IPackageManager getPackageManager() {
         return AppGlobals.getPackageManager();
     }
 
-    PackageManagerInternal getPackageManagerInternalLocked() {
+    @VisibleForTesting
+    public PackageManagerInternal getPackageManagerInternalLocked() {
         if (mPackageManagerInt == null) {
             mPackageManagerInt = LocalServices.getService(PackageManagerInternal.class);
         }
@@ -7682,7 +7710,7 @@
      *
      * @return {@code true} if this succeeded.
      */
-    static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) {
+    public static boolean scheduleAsRegularPriority(int tid, boolean suppressLogs) {
         try {
             Process.setThreadScheduler(tid, Process.SCHED_OTHER, 0);
             return true;
@@ -7706,7 +7734,7 @@
      *
      * @return {@code true} if this succeeded.
      */
-    static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) {
+    public static boolean scheduleAsFifoPriority(int tid, boolean suppressLogs) {
         try {
             Process.setThreadScheduler(tid, Process.SCHED_FIFO | Process.SCHED_RESET_ON_FORK, 1);
             return true;
@@ -10458,11 +10486,11 @@
         ArrayList<Integer> objects;
         boolean all;
 
-        ItemMatcher() {
+        public ItemMatcher() {
             all = true;
         }
 
-        void build(String name) {
+        public void build(String name) {
             ComponentName componentName = ComponentName.unflattenFromString(name);
             if (componentName != null) {
                 if (components == null) {
@@ -10491,7 +10519,7 @@
             }
         }
 
-        int build(String[] args, int opti) {
+        public int build(String[] args, int opti) {
             for (; opti<args.length; opti++) {
                 String name = args[opti];
                 if ("--".equals(name)) {
@@ -10502,7 +10530,7 @@
             return opti;
         }
 
-        boolean match(Object object, ComponentName comp) {
+        public boolean match(Object object, ComponentName comp) {
             if (all) {
                 return true;
             }
@@ -18464,7 +18492,7 @@
     }
 
     @VisibleForTesting
-    final class LocalService extends ActivityManagerInternal {
+    public final class LocalService extends ActivityManagerInternal {
         @Override
         public String checkContentProviderAccess(String authority, int userId) {
             return ActivityManagerService.this.checkContentProviderAccess(authority, userId);
diff --git a/services/core/java/com/android/server/am/AppErrors.java b/services/core/java/com/android/server/am/AppErrors.java
index 44f69b1..dd3f3b5 100644
--- a/services/core/java/com/android/server/am/AppErrors.java
+++ b/services/core/java/com/android/server/am/AppErrors.java
@@ -17,12 +17,13 @@
 package com.android.server.am;
 
 import static android.app.ActivityTaskManager.INVALID_TASK_ID;
+import static android.content.pm.ApplicationInfo.FLAG_SYSTEM;
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.am.ActivityManagerService.MY_PID;
 import static com.android.server.am.ActivityManagerService.SYSTEM_DEBUGGABLE;
-import static com.android.server.am.ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE;
-import static com.android.server.am.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
+import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE;
+import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
 
 import android.app.ActivityManager;
 import android.app.ActivityOptions;
@@ -37,7 +38,6 @@
 import android.os.Binder;
 import android.os.Message;
 import android.os.Process;
-import android.os.RemoteException;
 import android.os.SystemClock;
 import android.os.SystemProperties;
 import android.os.UserHandle;
@@ -54,12 +54,11 @@
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto;
 import com.android.server.RescueParty;
-import com.android.server.Watchdog;
+import com.android.server.wm.WindowProcessController;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
 import java.util.Collections;
-import java.util.Set;
 
 /**
  * Controls error conditions in applications.
@@ -619,7 +618,7 @@
         report.installerPackageName = r.errorReportReceiver.getPackageName();
         report.processName = r.processName;
         report.time = timeMillis;
-        report.systemApp = (r.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
+        report.systemApp = (r.info.flags & FLAG_SYSTEM) != 0;
 
         if (r.isCrashing() || r.forceCrashReport) {
             report.type = ApplicationErrorReport.TYPE_CRASH;
@@ -732,7 +731,7 @@
         final WindowProcessController proc = app.getWindowProcessController();
         final WindowProcessController homeProc = mService.mAtmInternal.getHomeProcess();
         if (proc == homeProc && proc.hasActivities()
-                && (homeProc.mInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
+                && (((ProcessRecord) homeProc.mOwner).info.flags & FLAG_SYSTEM) == 0) {
             proc.clearPackagePreferredForHomeActivities();
         }
 
diff --git a/services/core/java/com/android/server/am/AppTimeTracker.java b/services/core/java/com/android/server/am/AppTimeTracker.java
index 772865d..debe0a9 100644
--- a/services/core/java/com/android/server/am/AppTimeTracker.java
+++ b/services/core/java/com/android/server/am/AppTimeTracker.java
@@ -122,7 +122,7 @@
         }
     }
 
-    void writeToProto(ProtoOutputStream proto, long fieldId, boolean details) {
+    public void writeToProto(ProtoOutputStream proto, long fieldId, boolean details) {
         final long token = proto.start(fieldId);
         proto.write(AppTimeTrackerProto.RECEIVER, mReceiver.toString());
         proto.write(AppTimeTrackerProto.TOTAL_DURATION_MS, mTotalTime);
diff --git a/services/core/java/com/android/server/am/BaseErrorDialog.java b/services/core/java/com/android/server/am/BaseErrorDialog.java
index cd4d6a3..aabb587 100644
--- a/services/core/java/com/android/server/am/BaseErrorDialog.java
+++ b/services/core/java/com/android/server/am/BaseErrorDialog.java
@@ -26,7 +26,7 @@
 import android.view.WindowManager;
 import android.widget.Button;
 
-class BaseErrorDialog extends AlertDialog {
+public class BaseErrorDialog extends AlertDialog {
     private static final int ENABLE_BUTTONS = 0;
     private static final int DISABLE_BUTTONS = 1;
 
diff --git a/services/core/java/com/android/server/am/ConnectionRecord.java b/services/core/java/com/android/server/am/ConnectionRecord.java
index 1242ed6..37d07bb 100644
--- a/services/core/java/com/android/server/am/ConnectionRecord.java
+++ b/services/core/java/com/android/server/am/ConnectionRecord.java
@@ -27,6 +27,7 @@
 
 import com.android.internal.app.procstats.AssociationState;
 import com.android.internal.app.procstats.ProcessStats;
+import com.android.server.wm.ActivityServiceConnectionsHolder;
 
 import java.io.PrintWriter;
 
diff --git a/services/core/java/com/android/server/am/CoreSettingsObserver.java b/services/core/java/com/android/server/am/CoreSettingsObserver.java
index 48e26ed..968c17f 100644
--- a/services/core/java/com/android/server/am/CoreSettingsObserver.java
+++ b/services/core/java/com/android/server/am/CoreSettingsObserver.java
@@ -59,6 +59,7 @@
         sGlobalSettingToTypeMap.put(Settings.Global.ENABLE_GPU_DEBUG_LAYERS, int.class);
         sGlobalSettingToTypeMap.put(Settings.Global.GPU_DEBUG_APP, String.class);
         sGlobalSettingToTypeMap.put(Settings.Global.GPU_DEBUG_LAYERS, String.class);
+        sGlobalSettingToTypeMap.put(Settings.Global.GPU_DEBUG_LAYERS_GLES, String.class);
         sGlobalSettingToTypeMap.put(Settings.Global.GPU_DEBUG_LAYER_APP, String.class);
         // add other global settings here...
     }
diff --git a/services/core/java/com/android/server/am/MemoryStatUtil.java b/services/core/java/com/android/server/am/MemoryStatUtil.java
index f77be5b..c978c13 100644
--- a/services/core/java/com/android/server/am/MemoryStatUtil.java
+++ b/services/core/java/com/android/server/am/MemoryStatUtil.java
@@ -16,7 +16,7 @@
 
 package com.android.server.am;
 
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_METRICS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_METRICS;
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
 
@@ -273,18 +273,18 @@
 
     public static final class MemoryStat {
         /** Number of page faults */
-        long pgfault;
+        public long pgfault;
         /** Number of major page faults */
-        long pgmajfault;
+        public long pgmajfault;
         /** Number of bytes of anonymous and swap cache memory */
-        long rssInBytes;
+        public long rssInBytes;
         /** Number of bytes of page cache memory */
-        long cacheInBytes;
+        public long cacheInBytes;
         /** Number of bytes of swap usage */
-        long swapInBytes;
+        public long swapInBytes;
         /** Number of bytes of peak anonymous and swap cache memory */
-        long rssHighWatermarkInBytes;
+        public long rssHighWatermarkInBytes;
         /** Device time when the processes started. */
-        long startTimeNanos;
+        public long startTimeNanos;
     }
 }
diff --git a/services/core/java/com/android/server/am/PendingIntentController.java b/services/core/java/com/android/server/am/PendingIntentController.java
index a9c00a7..a5d4738 100644
--- a/services/core/java/com/android/server/am/PendingIntentController.java
+++ b/services/core/java/com/android/server/am/PendingIntentController.java
@@ -43,6 +43,7 @@
 import com.android.internal.util.function.pooled.PooledLambda;
 import com.android.server.LocalServices;
 import com.android.server.wm.ActivityTaskManagerInternal;
+import com.android.server.wm.SafeActivityOptions;
 
 import java.io.PrintWriter;
 import java.lang.ref.WeakReference;
@@ -84,8 +85,8 @@
         }
     }
 
-    PendingIntentRecord getIntentSender(int type, String packageName, int callingUid, int userId,
-            IBinder token, String resultWho, int requestCode, Intent[] intents,
+    public PendingIntentRecord getIntentSender(int type, String packageName, int callingUid,
+            int userId, IBinder token, String resultWho, int requestCode, Intent[] intents,
             String[] resolvedTypes, int flags, Bundle bOptions) {
         synchronized (mLock) {
             if (DEBUG_MU) Slog.v(TAG_MU, "getIntentSender(): uid=" + callingUid);
diff --git a/services/core/java/com/android/server/am/PendingIntentRecord.java b/services/core/java/com/android/server/am/PendingIntentRecord.java
index 2dcddff..447243b 100644
--- a/services/core/java/com/android/server/am/PendingIntentRecord.java
+++ b/services/core/java/com/android/server/am/PendingIntentRecord.java
@@ -39,6 +39,7 @@
 
 import com.android.internal.os.IResultReceiver;
 import com.android.internal.util.function.pooled.PooledLambda;
+import com.android.server.wm.SafeActivityOptions;
 
 import java.io.PrintWriter;
 import java.lang.ref.WeakReference;
@@ -50,7 +51,7 @@
     final PendingIntentController controller;
     final Key key;
     final int uid;
-    final WeakReference<PendingIntentRecord> ref;
+    public final WeakReference<PendingIntentRecord> ref;
     boolean sent = false;
     boolean canceled = false;
     private ArrayMap<IBinder, Long> whitelistDuration;
@@ -248,7 +249,7 @@
                 requiredPermission, null, null, 0, 0, 0, options);
     }
 
-    int sendInner(int code, Intent intent, String resolvedType, IBinder whitelistToken,
+    public int sendInner(int code, Intent intent, String resolvedType, IBinder whitelistToken,
             IIntentReceiver finishedReceiver, String requiredPermission, IBinder resultTo,
             String resultWho, int requestCode, int flagsMask, int flagsValues, Bundle options) {
         if (intent != null) intent.setDefusable(true);
@@ -450,7 +451,7 @@
         }
     }
 
-    void dump(PrintWriter pw, String prefix) {
+    public void dump(PrintWriter pw, String prefix) {
         pw.print(prefix); pw.print("uid="); pw.print(uid);
                 pw.print(" packageName="); pw.print(key.packageName);
                 pw.print(" type="); pw.print(key.typeName());
diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java
index 6741dc0..93c8391 100644
--- a/services/core/java/com/android/server/am/ProcessList.java
+++ b/services/core/java/com/android/server/am/ProcessList.java
@@ -92,6 +92,7 @@
 import com.android.server.ServiceThread;
 import com.android.server.Watchdog;
 import com.android.server.pm.dex.DexManager;
+import com.android.server.wm.ActivityServiceConnectionsHolder;
 import com.android.server.wm.WindowManagerService;
 
 import dalvik.system.VMRuntime;
@@ -212,7 +213,7 @@
     // Activity manager's version of Process.THREAD_GROUP_DEFAULT
     static final int SCHED_GROUP_DEFAULT = 2;
     // Activity manager's version of Process.THREAD_GROUP_TOP_APP
-    static final int SCHED_GROUP_TOP_APP = 3;
+    public static final int SCHED_GROUP_TOP_APP = 3;
     // Activity manager's version of Process.THREAD_GROUP_TOP_APP
     // Disambiguate between actual top app and processes bound to the top app
     static final int SCHED_GROUP_TOP_APP_BOUND = 4;
@@ -2523,9 +2524,13 @@
                     currApp.importanceReasonImportance =
                             ActivityManager.RunningAppProcessInfo.procStateToImportance(
                                     app.adjSourceProcState);
-                } else if (app.adjSource instanceof ActivityRecord) {
-                    ActivityRecord r = (ActivityRecord)app.adjSource;
-                    if (r.app != null) currApp.importanceReasonPid = r.app.getPid();
+                } else if (app.adjSource instanceof ActivityServiceConnectionsHolder) {
+                    final ActivityServiceConnectionsHolder r =
+                            (ActivityServiceConnectionsHolder) app.adjSource;
+                    final int pid = r.getActivityPid();
+                    if (pid != -1) {
+                        currApp.importanceReasonPid = pid;
+                    }
                 }
                 if (app.adjTarget instanceof ComponentName) {
                     currApp.importanceReasonComponent = (ComponentName)app.adjTarget;
diff --git a/services/core/java/com/android/server/am/ProcessRecord.java b/services/core/java/com/android/server/am/ProcessRecord.java
index 683754c..bb87ad0 100644
--- a/services/core/java/com/android/server/am/ProcessRecord.java
+++ b/services/core/java/com/android/server/am/ProcessRecord.java
@@ -33,7 +33,6 @@
 import android.content.Context;
 import android.content.pm.ApplicationInfo;
 import android.content.res.CompatibilityInfo;
-import android.content.res.Configuration;
 import android.os.Binder;
 import android.os.Debug;
 import android.os.IBinder;
@@ -58,7 +57,8 @@
 import com.android.internal.app.procstats.ProcessStats;
 import com.android.internal.os.BatteryStatsImpl;
 import com.android.internal.os.ProcessCpuTracker;
-import com.android.server.Watchdog;
+import com.android.server.wm.WindowProcessController;
+import com.android.server.wm.WindowProcessListener;
 
 import java.io.File;
 import java.io.IOException;
diff --git a/services/core/java/com/android/server/connectivity/NetdEventListenerService.java b/services/core/java/com/android/server/connectivity/NetdEventListenerService.java
index 4f31e53..422f556 100644
--- a/services/core/java/com/android/server/connectivity/NetdEventListenerService.java
+++ b/services/core/java/com/android/server/connectivity/NetdEventListenerService.java
@@ -208,7 +208,8 @@
 
         for (INetdEventCallback callback : mNetdEventCallbackList) {
             if (callback != null) {
-                callback.onDnsEvent(hostname, ipAddresses, ipAddressesCount, timestamp, uid);
+                callback.onDnsEvent(netId, eventType, returnCode, hostname, ipAddresses,
+                        ipAddressesCount, timestamp, uid);
             }
         }
     }
diff --git a/services/core/java/com/android/server/net/watchlist/NetworkWatchlistService.java b/services/core/java/com/android/server/net/watchlist/NetworkWatchlistService.java
index 29b1339..fa90e90 100644
--- a/services/core/java/com/android/server/net/watchlist/NetworkWatchlistService.java
+++ b/services/core/java/com/android/server/net/watchlist/NetworkWatchlistService.java
@@ -142,8 +142,8 @@
 
     private final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
         @Override
-        public void onDnsEvent(String hostname, String[] ipAddresses, int ipAddressesCount,
-                long timestamp, int uid) {
+        public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
+                String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
             if (!mIsLoggingEnabled) {
                 return;
             }
diff --git a/services/core/java/com/android/server/notification/ZenModeHelper.java b/services/core/java/com/android/server/notification/ZenModeHelper.java
index fc9bd37..f279af0 100644
--- a/services/core/java/com/android/server/notification/ZenModeHelper.java
+++ b/services/core/java/com/android/server/notification/ZenModeHelper.java
@@ -96,7 +96,7 @@
     private final SettingsObserver mSettingsObserver;
     @VisibleForTesting protected final AppOpsManager mAppOps;
     @VisibleForTesting protected final NotificationManager mNotificationManager;
-    protected ZenModeConfig mDefaultConfig;
+    @VisibleForTesting protected ZenModeConfig mDefaultConfig;
     private final ArrayList<Callback> mCallbacks = new ArrayList<Callback>();
     private final ZenModeFiltering mFiltering;
     protected final RingerModeDelegate mRingerModeDelegate = new
@@ -309,9 +309,6 @@
             newConfig = mConfig.copy();
             ZenRule rule = new ZenRule();
             populateZenRule(automaticZenRule, rule, true);
-            if (newConfig.automaticRules.put(rule.id, rule) != null) {
-                rule.modified = true;
-            }
             if (setConfigLocked(newConfig, reason, rule.component, true)) {
                 return rule.id;
             } else {
@@ -341,9 +338,6 @@
                 }
             }
             populateZenRule(automaticZenRule, rule, false);
-            if (newConfig.automaticRules.put(ruleId, rule) != null) {
-                rule.modified = true;
-            }
             return setConfigLocked(newConfig, reason, rule.component, true);
         }
     }
@@ -431,13 +425,16 @@
         updateDefaultAutomaticRuleNames();
         for (ZenRule defaultRule : mDefaultConfig.automaticRules.values()) {
             ZenRule currRule = mConfig.automaticRules.get(defaultRule.id);
-            // if default rule wasn't modified, use localized name instead of previous
-            if (currRule != null && !currRule.modified && !defaultRule.name.equals(currRule.name)) {
-                if (canManageAutomaticZenRule(defaultRule)) {
+            // if default rule wasn't user-modified nor enabled, use localized name
+            // instead of previous system name
+            if (currRule != null && !currRule.modified && !currRule.enabled
+                    && !defaultRule.name.equals(currRule.name)) {
+                if (canManageAutomaticZenRule(currRule)) {
                     if (DEBUG) Slog.d(TAG, "Locale change - updating default zen rule name "
                             + "from " + currRule.name + " to " + defaultRule.name);
                     // update default rule (if locale changed, name of rule will change)
-                    updateAutomaticZenRule(defaultRule.id, createAutomaticZenRule(defaultRule),
+                    currRule.name = defaultRule.name;
+                    updateAutomaticZenRule(defaultRule.id, createAutomaticZenRule(currRule),
                             "locale changed");
                 }
             }
@@ -481,6 +478,7 @@
         rule.condition = null;
         rule.conditionId = automaticZenRule.getConditionId();
         rule.enabled = automaticZenRule.isEnabled();
+        rule.modified = automaticZenRule.isModified();
         if (automaticZenRule.getZenPolicy() != null) {
             rule.zenPolicy = automaticZenRule.getZenPolicy();
         }
diff --git a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
index 45cb477..aae7b95 100644
--- a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
@@ -344,40 +344,43 @@
     @SafeVarargs
     private final void grantIgnoringSystemPackage(String packageName, int userId,
             Set<String>... permissionGroups) {
-        grantPermissionsToSystemPackage(packageName, userId, false, true, permissionGroups);
+        grantPermissionsToPackage(
+                packageName, userId, true /* ignoreSystemPackage */, permissionGroups);
     }
 
     @SafeVarargs
     private final void grantSystemFixedPermissionsToSystemPackage(String packageName, int userId,
             Set<String>... permissionGroups) {
-        grantPermissionsToSystemPackage(packageName, userId, true, false, permissionGroups);
+        grantPermissionsToSystemPackage(
+                packageName, userId, true /* systemFixed */, permissionGroups);
     }
 
     @SafeVarargs
     private final void grantPermissionsToSystemPackage(
             String packageName, int userId, Set<String>... permissionGroups) {
-        grantPermissionsToSystemPackage(packageName, userId, false, false, permissionGroups);
+        grantPermissionsToSystemPackage(
+                packageName, userId, false /* systemFixed */, permissionGroups);
     }
 
     @SafeVarargs
     private final void grantPermissionsToSystemPackage(String packageName, int userId,
-            boolean systemFixed, boolean ignoreSystemPackage, Set<String>... permissionGroups) {
-        if (!ignoreSystemPackage && !isSystemPackage(packageName)) {
+            boolean systemFixed, Set<String>... permissionGroups) {
+        if (!isSystemPackage(packageName)) {
             return;
         }
-        grantRuntimePermissionsToPackage(getSystemPackageInfo(packageName),
-                userId, systemFixed, ignoreSystemPackage, permissionGroups);
+        grantPermissionsToPackage(getSystemPackageInfo(packageName),
+                userId, systemFixed, false /* ignoreSystemPackage */, permissionGroups);
     }
 
     @SafeVarargs
-    private final void grantRuntimePermissionsToPackage(String packageName, int userId,
-            boolean systemFixed, boolean ignoreSystemPackage, Set<String>... permissionGroups) {
-        grantRuntimePermissionsToPackage(getPackageInfo(packageName),
-                userId, systemFixed, ignoreSystemPackage, permissionGroups);
+    private final void grantPermissionsToPackage(String packageName, int userId,
+            boolean ignoreSystemPackage, Set<String>... permissionGroups) {
+        grantPermissionsToPackage(getPackageInfo(packageName),
+                userId, false /* systemFixed */, ignoreSystemPackage, permissionGroups);
     }
 
     @SafeVarargs
-    private final void grantRuntimePermissionsToPackage(PackageInfo packageName, int userId,
+    private final void grantPermissionsToPackage(PackageInfo packageName, int userId,
             boolean systemFixed, boolean ignoreSystemPackage, Set<String>... permissionGroups) {
         if (packageName == null) return;
         if (doesPackageSupportRuntimePermissions(packageName)) {
@@ -589,9 +592,8 @@
                 browserPackage = null;
             }
         }
-        grantRuntimePermissionsToPackage(browserPackage, userId,
-                false /* systemFixed */, false /* ignoreSystemPackage */,
-                LOCATION_PERMISSIONS);
+        grantPermissionsToPackage(browserPackage, userId,
+                false /* ignoreSystemPackage */, LOCATION_PERMISSIONS);
 
         // Voice interaction
         if (voiceInteractPackageNames != null) {
@@ -786,7 +788,7 @@
             return;
         }
         Log.i(TAG, "Granting permissions to sim call manager for user:" + userId);
-        grantRuntimePermissionsToPackage(packageName, userId, false, false,
+        grantPermissionsToPackage(packageName, userId, false /* ignoreSystemPackage */,
                 PHONE_PERMISSIONS, MICROPHONE_PERMISSIONS);
     }
 
diff --git a/services/core/java/com/android/server/wm/AccessibilityController.java b/services/core/java/com/android/server/wm/AccessibilityController.java
index 9edb3d0..e4d1cfe 100644
--- a/services/core/java/com/android/server/wm/AccessibilityController.java
+++ b/services/core/java/com/android/server/wm/AccessibilityController.java
@@ -735,7 +735,7 @@
                 }
 
                 public void setShown(boolean shown, boolean animate) {
-                    synchronized (mService.mWindowMap) {
+                    synchronized (mService.mGlobalLock) {
                         if (mShown == shown) {
                             return;
                         }
@@ -750,13 +750,13 @@
                 @SuppressWarnings("unused")
                 // Called reflectively from an animator.
                 public int getAlpha() {
-                    synchronized (mService.mWindowMap) {
+                    synchronized (mService.mGlobalLock) {
                         return mAlpha;
                     }
                 }
 
                 public void setAlpha(int alpha) {
-                    synchronized (mService.mWindowMap) {
+                    synchronized (mService.mGlobalLock) {
                         if (mAlpha == alpha) {
                             return;
                         }
@@ -769,7 +769,7 @@
                 }
 
                 public void setBounds(Region bounds) {
-                    synchronized (mService.mWindowMap) {
+                    synchronized (mService.mGlobalLock) {
                         if (mBounds.equals(bounds)) {
                             return;
                         }
@@ -782,7 +782,7 @@
                 }
 
                 public void updateSize() {
-                    synchronized (mService.mWindowMap) {
+                    synchronized (mService.mGlobalLock) {
                         mWindowManager.getDefaultDisplay().getRealSize(mTempPoint);
                         mSurfaceControl.setSize(mTempPoint.x, mTempPoint.y);
                         invalidate(mDirtyRect);
@@ -801,7 +801,7 @@
 
                 /** NOTE: This has to be called within a surface transaction. */
                 public void drawIfNeeded() {
-                    synchronized (mService.mWindowMap) {
+                    synchronized (mService.mGlobalLock) {
                         if (!mInvalidated) {
                             return;
                         }
@@ -948,7 +948,7 @@
                     } break;
 
                     case MESSAGE_SHOW_MAGNIFIED_REGION_BOUNDS_IF_NEEDED : {
-                        synchronized (mService.mWindowMap) {
+                        synchronized (mService.mGlobalLock) {
                             if (mMagnifedViewport.isMagnifyingLocked()
                                     || isForceShowingMagnifiableBoundsLocked()) {
                                 mMagnifedViewport.setMagnifiedRegionBorderShownLocked(true, true);
@@ -1039,7 +1039,7 @@
             boolean windowsChanged = false;
             List<WindowInfo> windows = new ArrayList<WindowInfo>();
 
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 // Do not send the windows if there is no current focus as
                 // the window manager is still looking for where to put it.
                 // We will do the work when we get a focus change callback.
diff --git a/services/core/java/com/android/server/am/ActivityDisplay.java b/services/core/java/com/android/server/wm/ActivityDisplay.java
similarity index 98%
rename from services/core/java/com/android/server/am/ActivityDisplay.java
rename to services/core/java/com/android/server/wm/ActivityDisplay.java
index 05293b5..5fb1def 100644
--- a/services/core/java/com/android/server/am/ActivityDisplay.java
+++ b/services/core/java/com/android/server/wm/ActivityDisplay.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityTaskManager.INVALID_STACK_ID;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
@@ -37,16 +37,16 @@
 import static com.android.server.am.ActivityDisplayProto.ID;
 import static com.android.server.am.ActivityDisplayProto.RESUMED_ACTIVITY;
 import static com.android.server.am.ActivityDisplayProto.STACKS;
-import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
-import static com.android.server.am.ActivityStackSupervisor.FindTaskResult;
-import static com.android.server.am.ActivityStackSupervisor.TAG_STATES;
-import static com.android.server.am.ActivityStackSupervisor.TAG_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_STACK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_STATES;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
+import static com.android.server.wm.ActivityStackSupervisor.FindTaskResult;
+import static com.android.server.wm.ActivityStackSupervisor.TAG_STATES;
+import static com.android.server.wm.ActivityStackSupervisor.TAG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STATES;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
 
 import android.annotation.Nullable;
 import android.app.ActivityOptions;
@@ -59,10 +59,7 @@
 import android.view.Display;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.server.wm.ActivityTaskManagerInternal;
-import com.android.server.wm.ConfigurationContainer;
-import com.android.server.wm.DisplayWindowController;
-import com.android.server.wm.WindowContainerListener;
+import com.android.server.am.EventLogTags;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -1038,8 +1035,6 @@
 
         releaseSelfIfNeeded();
 
-        mSupervisor.getKeyguardController().onDisplayRemoved(mDisplayId);
-
         if (!mAllSleepTokens.isEmpty()) {
             mSupervisor.mSleepTokens.removeAll(mAllSleepTokens);
             mAllSleepTokens.clear();
@@ -1052,6 +1047,7 @@
             mWindowContainerController.removeContainer();
             mWindowContainerController = null;
             mSupervisor.removeChild(this);
+            mSupervisor.getKeyguardController().onDisplayRemoved(mDisplayId);
         }
     }
 
diff --git a/services/core/java/com/android/server/am/ActivityMetricsLogger.java b/services/core/java/com/android/server/wm/ActivityMetricsLogger.java
similarity index 99%
rename from services/core/java/com/android/server/am/ActivityMetricsLogger.java
rename to services/core/java/com/android/server/wm/ActivityMetricsLogger.java
index a0dd878..8bde7dd 100644
--- a/services/core/java/com/android/server/am/ActivityMetricsLogger.java
+++ b/services/core/java/com/android/server/wm/ActivityMetricsLogger.java
@@ -1,4 +1,4 @@
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.START_SUCCESS;
 import static android.app.ActivityManager.START_TASK_TO_FRONT;
@@ -72,9 +72,9 @@
 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_REPORTED_DRAWN_NO_BUNDLE;
 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_REPORTED_DRAWN_WITH_BUNDLE;
 import static com.android.internal.logging.nano.MetricsProto.MetricsEvent.TYPE_TRANSITION_WARM_LAUNCH;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_METRICS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_METRICS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.am.EventLogTags.AM_ACTIVITY_LAUNCH_TIME;
 import static com.android.server.am.MemoryStatUtil.MemoryStat;
 import static com.android.server.am.MemoryStatUtil.readMemoryStatFromFilesystem;
diff --git a/services/core/java/com/android/server/am/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java
similarity index 98%
rename from services/core/java/com/android/server/am/ActivityRecord.java
rename to services/core/java/com/android/server/wm/ActivityRecord.java
index 47b4f47..8223693 100644
--- a/services/core/java/com/android/server/am/ActivityRecord.java
+++ b/services/core/java/com/android/server/wm/ActivityRecord.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
 import static android.app.ActivityManager.TaskDescription.ATTR_TASKDESCRIPTION_PREFIX;
@@ -75,20 +75,20 @@
 import static android.view.Display.INVALID_DISPLAY;
 import static android.view.WindowManagerPolicyConstants.NAV_BAR_LEFT;
 
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_SAVED_STATE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_STATES;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_SAVED_STATE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_STATES;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SAVED_STATE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STATES;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SAVED_STATE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STATES;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.am.ActivityRecordProto.CONFIGURATION_CONTAINER;
 import static com.android.server.am.ActivityRecordProto.FRONT_OF_TASK;
 import static com.android.server.am.ActivityRecordProto.IDENTIFIER;
@@ -96,23 +96,23 @@
 import static com.android.server.am.ActivityRecordProto.STATE;
 import static com.android.server.am.ActivityRecordProto.TRANSLUCENT;
 import static com.android.server.am.ActivityRecordProto.VISIBLE;
-import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
-import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
-import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
-import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
-import static com.android.server.am.ActivityStack.LAUNCH_TICK;
-import static com.android.server.am.ActivityStack.LAUNCH_TICK_MSG;
-import static com.android.server.am.ActivityStack.PAUSE_TIMEOUT_MSG;
-import static com.android.server.am.ActivityStack.STOP_TIMEOUT_MSG;
-import static com.android.server.am.ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE;
-import static com.android.server.am.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
-import static com.android.server.am.ActivityTaskManagerService.RELAUNCH_REASON_WINDOWING_MODE_RESIZE;
+import static com.android.server.wm.ActivityStack.ActivityState.INITIALIZING;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSED;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSING;
+import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
+import static com.android.server.wm.ActivityStack.ActivityState.STOPPED;
+import static com.android.server.wm.ActivityStack.ActivityState.STOPPING;
+import static com.android.server.wm.ActivityStack.LAUNCH_TICK;
+import static com.android.server.wm.ActivityStack.LAUNCH_TICK_MSG;
+import static com.android.server.wm.ActivityStack.PAUSE_TIMEOUT_MSG;
+import static com.android.server.wm.ActivityStack.STOP_TIMEOUT_MSG;
+import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE;
+import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
+import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_WINDOWING_MODE_RESIZE;
 import static com.android.server.am.EventLogTags.AM_RELAUNCH_ACTIVITY;
 import static com.android.server.am.EventLogTags.AM_RELAUNCH_RESUME_ACTIVITY;
-import static com.android.server.am.TaskPersister.DEBUG;
-import static com.android.server.am.TaskPersister.IMAGE_EXTENSION;
+import static com.android.server.wm.TaskPersister.DEBUG;
+import static com.android.server.wm.TaskPersister.IMAGE_EXTENSION;
 import static android.app.ActivityTaskManager.INVALID_TASK_ID;
 import static com.android.server.wm.IdentifierProto.HASH_CODE;
 import static com.android.server.wm.IdentifierProto.TITLE;
@@ -177,13 +177,11 @@
 import com.android.internal.util.XmlUtils;
 import com.android.server.AttributeCache;
 import com.android.server.AttributeCache.Entry;
-import com.android.server.am.ActivityMetricsLogger.WindowingModeTransitionInfoSnapshot;
-import com.android.server.am.ActivityStack.ActivityState;
+import com.android.server.am.AppTimeTracker;
+import com.android.server.am.PendingIntentRecord;
+import com.android.server.wm.ActivityMetricsLogger.WindowingModeTransitionInfoSnapshot;
+import com.android.server.wm.ActivityStack.ActivityState;
 import com.android.server.uri.UriPermissionOwner;
-import com.android.server.wm.AppWindowContainerController;
-import com.android.server.wm.AppWindowContainerListener;
-import com.android.server.wm.ConfigurationContainer;
-import com.android.server.wm.TaskWindowContainerController;
 
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
diff --git a/services/core/java/com/android/server/am/ActivityResult.java b/services/core/java/com/android/server/wm/ActivityResult.java
similarity index 96%
rename from services/core/java/com/android/server/am/ActivityResult.java
rename to services/core/java/com/android/server/wm/ActivityResult.java
index 395918e..f2510de 100644
--- a/services/core/java/com/android/server/am/ActivityResult.java
+++ b/services/core/java/com/android/server/wm/ActivityResult.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.app.ResultInfo;
 import android.content.Intent;
diff --git a/services/core/java/com/android/server/am/ActivityServiceConnectionsHolder.java b/services/core/java/com/android/server/wm/ActivityServiceConnectionsHolder.java
similarity index 95%
rename from services/core/java/com/android/server/am/ActivityServiceConnectionsHolder.java
rename to services/core/java/com/android/server/wm/ActivityServiceConnectionsHolder.java
index b1ced29..ad46248 100644
--- a/services/core/java/com/android/server/am/ActivityServiceConnectionsHolder.java
+++ b/services/core/java/com/android/server/wm/ActivityServiceConnectionsHolder.java
@@ -14,10 +14,10 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
-import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
-import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSING;
+import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
 
 import java.io.PrintWriter;
 import java.util.HashSet;
diff --git a/services/core/java/com/android/server/am/ActivityStack.java b/services/core/java/com/android/server/wm/ActivityStack.java
similarity index 98%
rename from services/core/java/com/android/server/am/ActivityStack.java
rename to services/core/java/com/android/server/wm/ActivityStack.java
index d646e9a..a8b4a9d 100644
--- a/services/core/java/com/android/server/am/ActivityStack.java
+++ b/services/core/java/com/android/server/wm/ActivityStack.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ITaskStackListener.FORCED_RESIZEABLE_REASON_SPLIT_SCREEN;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
@@ -46,17 +46,16 @@
 import static android.view.WindowManager.TRANSIT_TASK_TO_BACK;
 import static android.view.WindowManager.TRANSIT_TASK_TO_FRONT;
 
-import static com.android.server.am.ActivityDisplay.POSITION_BOTTOM;
-import static com.android.server.am.ActivityDisplay.POSITION_TOP;
-import static com.android.server.am.ActivityManagerDebugConfig.POSTFIX_CLEANUP;
-import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
-import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
-import static com.android.server.am.ActivityStack.ActivityState.FINISHING;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
-import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
-import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
-import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
+import static com.android.server.wm.ActivityDisplay.POSITION_BOTTOM;
+import static com.android.server.wm.ActivityDisplay.POSITION_TOP;
+import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
+import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
+import static com.android.server.wm.ActivityStack.ActivityState.FINISHING;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSED;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSING;
+import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
+import static com.android.server.wm.ActivityStack.ActivityState.STOPPED;
+import static com.android.server.wm.ActivityStack.ActivityState.STOPPING;
 import static com.android.server.am.ActivityStackProto.BOUNDS;
 import static com.android.server.am.ActivityStackProto.CONFIGURATION_CONTAINER;
 import static com.android.server.am.ActivityStackProto.DISPLAY_ID;
@@ -64,45 +63,46 @@
 import static com.android.server.am.ActivityStackProto.ID;
 import static com.android.server.am.ActivityStackProto.RESUMED_ACTIVITY;
 import static com.android.server.am.ActivityStackProto.TASKS;
-import static com.android.server.am.ActivityStackSupervisor.FindTaskResult;
-import static com.android.server.am.ActivityStackSupervisor.PAUSE_IMMEDIATELY;
-import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
-import static com.android.server.am.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_ADD_REMOVE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_ALL;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_APP;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_CONTAINERS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_PAUSE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_RELEASE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_RESULTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_SAVED_STATE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_STACK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_STATES;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_TRANSITION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_USER_LEAVING;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_ADD_REMOVE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_APP;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_CONTAINERS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_PAUSE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_RELEASE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_RESULTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_SAVED_STATE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_STATES;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_TRANSITION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_USER_LEAVING;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.am.ActivityTaskManagerService.H.FIRST_ACTIVITY_STACK_MSG;
-import static com.android.server.am.ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE;
-import static com.android.server.am.ActivityTaskManagerService.RELAUNCH_REASON_WINDOWING_MODE_RESIZE;
+import static com.android.server.wm.ActivityStackSupervisor.FindTaskResult;
+import static com.android.server.wm.ActivityStackSupervisor.PAUSE_IMMEDIATELY;
+import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
+import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ADD_REMOVE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_APP;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CLEANUP;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONTAINERS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_PAUSE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RELEASE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RESULTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SAVED_STATE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STATES;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TRANSITION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_USER_LEAVING;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_ADD_REMOVE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_APP;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CLEANUP;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONTAINERS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_PAUSE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RELEASE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RESULTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SAVED_STATE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STATES;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TRANSITION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_USER_LEAVING;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerService.H.FIRST_ACTIVITY_STACK_MSG;
+import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_FREE_RESIZE;
+import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_WINDOWING_MODE_RESIZE;
 
 import static java.lang.Integer.MAX_VALUE;
 
@@ -154,12 +154,11 @@
 import com.android.internal.app.IVoiceInteractor;
 import com.android.internal.util.function.pooled.PooledLambda;
 import com.android.server.Watchdog;
+import com.android.server.am.ActivityManagerService;
 import com.android.server.am.ActivityManagerService.ItemMatcher;
-import com.android.server.wm.ConfigurationContainer;
-import com.android.server.wm.DisplayWindowController;
-import com.android.server.wm.StackWindowController;
-import com.android.server.wm.StackWindowListener;
-import com.android.server.wm.WindowManagerService;
+import com.android.server.am.AppTimeTracker;
+import com.android.server.am.EventLogTags;
+import com.android.server.am.PendingIntentRecord;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
diff --git a/services/core/java/com/android/server/am/ActivityStackSupervisor.java b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
similarity index 98%
rename from services/core/java/com/android/server/am/ActivityStackSupervisor.java
rename to services/core/java/com/android/server/wm/ActivityStackSupervisor.java
index 695fac2..77b331e 100644
--- a/services/core/java/com/android/server/am/ActivityStackSupervisor.java
+++ b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.Manifest.permission.ACTIVITY_EMBEDDING;
 import static android.Manifest.permission.INTERNAL_SYSTEM_WINDOW;
@@ -59,14 +59,14 @@
 import static android.view.Display.TYPE_VIRTUAL;
 import static android.view.WindowManager.TRANSIT_DOCK_TASK_FROM_RECENTS;
 
-import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
-import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
-import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
-import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
-import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
-import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
+import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
+import static com.android.server.wm.ActivityStack.ActivityState.INITIALIZING;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSED;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSING;
+import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
+import static com.android.server.wm.ActivityStack.ActivityState.STOPPED;
+import static com.android.server.wm.ActivityStack.ActivityState.STOPPING;
+import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_MOVING;
 import static com.android.server.am.ActivityStackSupervisorProto.CONFIGURATION_CONTAINER;
 import static com.android.server.am.ActivityStackSupervisorProto.DISPLAYS;
 import static com.android.server.am.ActivityStackSupervisorProto.FOCUSED_STACK_ID;
@@ -74,34 +74,34 @@
 import static com.android.server.am.ActivityStackSupervisorProto.KEYGUARD_CONTROLLER;
 import static com.android.server.am.ActivityStackSupervisorProto.PENDING_ACTIVITIES;
 import static com.android.server.am.ActivityStackSupervisorProto.RESUMED_ACTIVITY;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_ALL;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_IDLE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_PAUSE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_RECENTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_RELEASE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_STACK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_STATES;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_IDLE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_PAUSE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_RELEASE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_STATES;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.am.ActivityTaskManagerService.ANIMATE;
-import static com.android.server.am.ActivityTaskManagerService.H.FIRST_SUPERVISOR_STACK_MSG;
-import static com.android.server.am.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
-import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
-import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
-import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
-import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
-import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
-import static com.android.server.am.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IDLE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_PAUSE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RELEASE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STATES;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IDLE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_PAUSE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RELEASE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STATES;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerService.ANIMATE;
+import static com.android.server.wm.ActivityTaskManagerService.H.FIRST_SUPERVISOR_STACK_MSG;
+import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
+import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
+import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
+import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
+import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
+import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
+import static com.android.server.wm.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
 
 import static java.lang.Integer.MAX_VALUE;
 
@@ -183,14 +183,12 @@
 import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.function.pooled.PooledLambda;
 import com.android.server.LocalServices;
-import com.android.server.am.ActivityStack.ActivityState;
+import com.android.server.am.ActivityManagerService;
+import com.android.server.am.AppTimeTracker;
+import com.android.server.am.EventLogTags;
+import com.android.server.am.UserState;
+import com.android.server.wm.ActivityStack.ActivityState;
 import com.android.server.wm.ActivityTaskManagerInternal.SleepToken;
-import com.android.server.wm.ConfigurationContainer;
-import com.android.server.wm.DisplayWindowController;
-import com.android.server.wm.PinnedStackWindowController;
-import com.android.server.wm.RootWindowContainerController;
-import com.android.server.wm.RootWindowContainerListener;
-import com.android.server.wm.WindowManagerService;
 
 import java.io.FileDescriptor;
 import java.io.IOException;
diff --git a/services/core/java/com/android/server/am/ActivityStartController.java b/services/core/java/com/android/server/wm/ActivityStartController.java
similarity index 97%
rename from services/core/java/com/android/server/am/ActivityStartController.java
rename to services/core/java/com/android/server/wm/ActivityStartController.java
index 3151ec9..904d9dd 100644
--- a/services/core/java/com/android/server/am/ActivityStartController.java
+++ b/services/core/java/com/android/server/wm/ActivityStartController.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.START_SUCCESS;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
@@ -22,8 +22,8 @@
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
 import static android.os.FactoryTest.FACTORY_TEST_LOW_LEVEL;
 
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
 
 import android.app.ActivityOptions;
 import android.app.IApplicationThread;
@@ -46,9 +46,11 @@
 import android.view.RemoteAnimationAdapter;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.server.am.ActivityStackSupervisor.PendingActivityLaunch;
-import com.android.server.am.ActivityStarter.DefaultFactory;
-import com.android.server.am.ActivityStarter.Factory;
+import com.android.server.am.ActivityManagerService;
+import com.android.server.am.PendingIntentRecord;
+import com.android.server.wm.ActivityStackSupervisor.PendingActivityLaunch;
+import com.android.server.wm.ActivityStarter.DefaultFactory;
+import com.android.server.wm.ActivityStarter.Factory;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
diff --git a/services/core/java/com/android/server/am/ActivityStartInterceptor.java b/services/core/java/com/android/server/wm/ActivityStartInterceptor.java
similarity index 99%
rename from services/core/java/com/android/server/am/ActivityStartInterceptor.java
rename to services/core/java/com/android/server/wm/ActivityStartInterceptor.java
index e51824f..ee5a43c 100644
--- a/services/core/java/com/android/server/am/ActivityStartInterceptor.java
+++ b/services/core/java/com/android/server/wm/ActivityStartInterceptor.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.INTENT_SENDER_ACTIVITY;
 import static android.app.ActivityOptions.ANIM_OPEN_CROSS_PROFILE_APPS;
@@ -57,6 +57,7 @@
 import com.android.internal.app.SuspendedAppActivity;
 import com.android.internal.app.UnlaunchableAppActivity;
 import com.android.server.LocalServices;
+import com.android.server.am.ActivityManagerService;
 
 /**
  * A class that contains activity intercepting logic for {@link ActivityStarter#startActivityLocked}
diff --git a/services/core/java/com/android/server/am/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java
similarity index 98%
rename from services/core/java/com/android/server/am/ActivityStarter.java
rename to services/core/java/com/android/server/wm/ActivityStarter.java
index 37ddaf9..e43a79a 100644
--- a/services/core/java/com/android/server/am/ActivityStarter.java
+++ b/services/core/java/com/android/server/wm/ActivityStarter.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.Activity.RESULT_CANCELED;
 import static android.app.ActivityManager.START_ABORTED;
@@ -53,28 +53,28 @@
 import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.Display.INVALID_DISPLAY;
 
-import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
-import static com.android.server.am.ActivityStackSupervisor.DEFER_RESUME;
-import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
-import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
-import static com.android.server.am.ActivityStackSupervisor.TAG_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_RESULTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_STACK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_USER_LEAVING;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_RESULTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_USER_LEAVING;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.am.ActivityTaskManagerService.ANIMATE;
+import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
+import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
+import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
+import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
+import static com.android.server.wm.ActivityStackSupervisor.TAG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_PERMISSIONS_REVIEW;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RESULTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_USER_LEAVING;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RESULTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_USER_LEAVING;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerService.ANIMATE;
 import static com.android.server.am.EventLogTags.AM_NEW_INTENT;
-import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
-import static com.android.server.am.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
+import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
+import static com.android.server.wm.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT;
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -112,8 +112,10 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.app.HeavyWeightSwitcherActivity;
 import com.android.internal.app.IVoiceInteractor;
-import com.android.server.am.ActivityStackSupervisor.PendingActivityLaunch;
-import com.android.server.am.LaunchParamsController.LaunchParams;
+import com.android.server.am.EventLogTags;
+import com.android.server.am.PendingIntentRecord;
+import com.android.server.wm.ActivityStackSupervisor.PendingActivityLaunch;
+import com.android.server.wm.LaunchParamsController.LaunchParams;
 import com.android.server.pm.InstantAppResolver;
 
 import java.io.PrintWriter;
diff --git a/services/core/java/com/android/server/am/ActivityTaskManagerDebugConfig.java b/services/core/java/com/android/server/wm/ActivityTaskManagerDebugConfig.java
similarity index 89%
rename from services/core/java/com/android/server/am/ActivityTaskManagerDebugConfig.java
rename to services/core/java/com/android/server/wm/ActivityTaskManagerDebugConfig.java
index 4f2a254..7f09a07 100644
--- a/services/core/java/com/android/server/am/ActivityTaskManagerDebugConfig.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerDebugConfig.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 /**
  * Common class for the various debug {@link android.util.Log} output configuration relating to
@@ -44,7 +44,7 @@
     private static final boolean DEBUG_ALL_ACTIVITIES = DEBUG_ALL || false;
 
     static final boolean DEBUG_ADD_REMOVE = DEBUG_ALL_ACTIVITIES || false;
-    static final boolean DEBUG_CONFIGURATION = DEBUG_ALL || false;
+    public static final boolean DEBUG_CONFIGURATION = DEBUG_ALL || false;
     static final boolean DEBUG_CONTAINERS = DEBUG_ALL_ACTIVITIES || false;
     static final boolean DEBUG_FOCUS = false;
     static final boolean DEBUG_IMMERSIVE = DEBUG_ALL || false;
@@ -55,7 +55,7 @@
     static final boolean DEBUG_SAVED_STATE = DEBUG_ALL_ACTIVITIES || false;
     static final boolean DEBUG_STACK = DEBUG_ALL || false;
     static final boolean DEBUG_STATES = DEBUG_ALL_ACTIVITIES || false;
-    static final boolean DEBUG_SWITCH = DEBUG_ALL || false;
+    public static final boolean DEBUG_SWITCH = DEBUG_ALL || false;
     static final boolean DEBUG_TASKS = DEBUG_ALL || false;
     static final boolean DEBUG_TRANSITION = DEBUG_ALL || false;
     static final boolean DEBUG_VISIBILITY = DEBUG_ALL || false;
@@ -65,8 +65,8 @@
     static final boolean DEBUG_USER_LEAVING = DEBUG_ALL || false;
     static final boolean DEBUG_PERMISSIONS_REVIEW = DEBUG_ALL || false;
     static final boolean DEBUG_RESULTS = DEBUG_ALL || false;
-    static final boolean DEBUG_CLEANUP = DEBUG_ALL || false;
-    static final boolean DEBUG_METRICS = DEBUG_ALL || false;
+    public static final boolean DEBUG_CLEANUP = DEBUG_ALL || false;
+    public static final boolean DEBUG_METRICS = DEBUG_ALL || false;
 
     static final String POSTFIX_APP = APPEND_CATEGORY_NAME ? "_App" : "";
     static final String POSTFIX_CLEANUP = (APPEND_CATEGORY_NAME) ? "_Cleanup" : "";
@@ -74,17 +74,17 @@
     static final String POSTFIX_RELEASE = APPEND_CATEGORY_NAME ? "_Release" : "";
     static final String POSTFIX_USER_LEAVING = APPEND_CATEGORY_NAME ? "_UserLeaving" : "";
     static final String POSTFIX_ADD_REMOVE = APPEND_CATEGORY_NAME ? "_AddRemove" : "";
-    static final String POSTFIX_CONFIGURATION = APPEND_CATEGORY_NAME ? "_Configuration" : "";
+    public static final String POSTFIX_CONFIGURATION = APPEND_CATEGORY_NAME ? "_Configuration" : "";
     static final String POSTFIX_CONTAINERS = APPEND_CATEGORY_NAME ? "_Containers" : "";
     static final String POSTFIX_FOCUS = APPEND_CATEGORY_NAME ? "_Focus" : "";
     static final String POSTFIX_IMMERSIVE = APPEND_CATEGORY_NAME ? "_Immersive" : "";
-    static final String POSTFIX_LOCKTASK = APPEND_CATEGORY_NAME ? "_LockTask" : "";
+    public static final String POSTFIX_LOCKTASK = APPEND_CATEGORY_NAME ? "_LockTask" : "";
     static final String POSTFIX_PAUSE = APPEND_CATEGORY_NAME ? "_Pause" : "";
     static final String POSTFIX_RECENTS = APPEND_CATEGORY_NAME ? "_Recents" : "";
     static final String POSTFIX_SAVED_STATE = APPEND_CATEGORY_NAME ? "_SavedState" : "";
     static final String POSTFIX_STACK = APPEND_CATEGORY_NAME ? "_Stack" : "";
     static final String POSTFIX_STATES = APPEND_CATEGORY_NAME ? "_States" : "";
-    static final String POSTFIX_SWITCH = APPEND_CATEGORY_NAME ? "_Switch" : "";
+    public static final String POSTFIX_SWITCH = APPEND_CATEGORY_NAME ? "_Switch" : "";
     static final String POSTFIX_TASKS = APPEND_CATEGORY_NAME ? "_Tasks" : "";
     static final String POSTFIX_TRANSITION = APPEND_CATEGORY_NAME ? "_Transition" : "";
     static final String POSTFIX_VISIBILITY = APPEND_CATEGORY_NAME ? "_Visibility" : "";
diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java b/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java
index 9a38f68..dcc7bc5 100644
--- a/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java
@@ -36,12 +36,8 @@
 import android.util.proto.ProtoOutputStream;
 
 import com.android.internal.app.IVoiceInteractor;
-import com.android.server.am.ActivityServiceConnectionsHolder;
 import com.android.server.am.PendingIntentRecord;
-import com.android.server.am.SafeActivityOptions;
-import com.android.server.am.TaskRecord;
 import com.android.server.am.UserState;
-import com.android.server.am.WindowProcessController;
 
 import java.io.FileDescriptor;
 import java.io.PrintWriter;
diff --git a/services/core/java/com/android/server/am/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
similarity index 98%
rename from services/core/java/com/android/server/am/ActivityTaskManagerService.java
rename to services/core/java/com/android/server/wm/ActivityTaskManagerService.java
index 9ddd58b..3ede8bc8 100644
--- a/services/core/java/com/android/server/am/ActivityTaskManagerService.java
+++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.Manifest.permission.BIND_VOICE_INTERACTION;
 import static android.Manifest.permission.CHANGE_CONFIGURATION;
@@ -82,40 +82,43 @@
 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.HOME_PROC;
 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.LAUNCHING_ACTIVITY;
 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC;
-import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.PREVIOUS_PROC_VISIBLE_TIME_MS;
+import static com.android.server.am.ActivityManagerServiceDumpProcessesProto
+        .PREVIOUS_PROC_VISIBLE_TIME_MS;
 import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.SCREEN_COMPAT_PACKAGES;
-import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.MODE;
-import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE;
-import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
-import static com.android.server.am.ActivityStackSupervisor.DEFER_RESUME;
-import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
-import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
-import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
-import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
-import static com.android.server.am.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_ALL;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_STACK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.am.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
-import static com.android.server.am.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
-import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
-import static com.android.server.am.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
-import static com.android.server.am.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
+import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
+        .MODE;
+import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage
+        .PACKAGE;
+import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
+import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME;
+import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_ONLY;
+import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
+import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
+import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
+import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_FOCUS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IMMERSIVE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_SWITCH;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_VISIBILITY;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_FOCUS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_IMMERSIVE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_STACK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_SWITCH;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_VISIBILITY;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerService.H.REPORT_TIME_TRACKER_MSG;
+import static com.android.server.wm.ActivityTaskManagerService.UiHandler.DISMISS_DIALOG_UI_MSG;
+import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
+import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT;
+import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE;
 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_CONTENT;
 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_DATA;
 import static com.android.server.wm.ActivityTaskManagerInternal.ASSIST_KEY_RECEIVER_EXTRAS;
@@ -248,14 +251,19 @@
 import com.android.server.SystemService;
 import com.android.server.SystemServiceManager;
 import com.android.server.Watchdog;
+import com.android.server.am.ActivityManagerService;
+import com.android.server.am.ActivityManagerServiceDumpActivitiesProto;
+import com.android.server.am.ActivityManagerServiceDumpProcessesProto;
+import com.android.server.am.AppTimeTracker;
+import com.android.server.am.BaseErrorDialog;
+import com.android.server.am.EventLogTags;
+import com.android.server.am.PendingIntentController;
+import com.android.server.am.PendingIntentRecord;
+import com.android.server.am.UserState;
 import com.android.server.firewall.IntentFirewall;
 import com.android.server.pm.UserManagerService;
 import com.android.server.uri.UriGrantsManagerInternal;
 import com.android.server.vr.VrManagerInternal;
-import com.android.server.wm.ActivityTaskManagerInternal;
-import com.android.server.wm.DisplayWindowController;
-import com.android.server.wm.PinnedStackWindowController;
-import com.android.server.wm.WindowManagerService;
 
 import java.io.BufferedReader;
 import java.io.File;
@@ -631,7 +639,7 @@
         mFontScaleSettingObserver = new FontScaleSettingObserver();
     }
 
-    void retrieveSettings(ContentResolver resolver) {
+    public void retrieveSettings(ContentResolver resolver) {
         final boolean freeformWindowManagement =
                 mContext.getPackageManager().hasSystemFeature(FEATURE_FREEFORM_WINDOW_MANAGEMENT)
                         || Settings.Global.getInt(
@@ -709,7 +717,7 @@
     }
 
     // TODO: Will be converted to WM lock once transition is complete.
-    void setActivityManagerService(Object globalLock, Looper looper,
+    public void setActivityManagerService(Object globalLock, Looper looper,
             IntentFirewall intentFirewall, PendingIntentController intentController) {
         mGlobalLock = globalLock;
         mH = new H(looper);
@@ -3874,7 +3882,7 @@
      * Check that we have the features required for VR-related API calls, and throw an exception if
      * not.
      */
-    void enforceSystemHasVrFeature() {
+    public void enforceSystemHasVrFeature() {
         if (!mContext.getPackageManager().hasSystemFeature(
                 PackageManager.FEATURE_VR_MODE_HIGH_PERFORMANCE)) {
             throw new UnsupportedOperationException("VR mode not supported on this device!");
@@ -4628,7 +4636,7 @@
                 UserHandle.USER_NULL, deferResume);
     }
 
-    void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
+    public void updatePersistentConfiguration(Configuration values, @UserIdInt int userId) {
         final long origId = Binder.clearCallingIdentity();
         try {
             synchronized (mGlobalLock) {
diff --git a/services/core/java/com/android/server/am/AppTaskImpl.java b/services/core/java/com/android/server/wm/AppTaskImpl.java
similarity index 97%
rename from services/core/java/com/android/server/am/AppTaskImpl.java
rename to services/core/java/com/android/server/wm/AppTaskImpl.java
index a1f1ff9..04fef02 100644
--- a/services/core/java/com/android/server/am/AppTaskImpl.java
+++ b/services/core/java/com/android/server/wm/AppTaskImpl.java
@@ -14,10 +14,10 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
-import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
-import static com.android.server.am.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
+import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
+import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
 
 import android.app.ActivityManager;
 import android.app.IAppTask;
diff --git a/services/core/java/com/android/server/wm/AppTransition.java b/services/core/java/com/android/server/wm/AppTransition.java
index 10a1be5..089640b 100644
--- a/services/core/java/com/android/server/wm/AppTransition.java
+++ b/services/core/java/com/android/server/wm/AppTransition.java
@@ -1924,7 +1924,7 @@
                 } catch (RemoteException e) {
                     Slog.w(TAG, "Failed to fetch app transition specs: " + e);
                 }
-                synchronized (mService.mWindowMap) {
+                synchronized (mService.mGlobalLock) {
                     mNextAppTransitionAnimationsSpecsPending = false;
                     overridePendingAppTransitionMultiThumb(specs,
                             mNextAppTransitionFutureCallback, null /* finishedCallback */,
@@ -2220,7 +2220,7 @@
     }
 
     private void handleAppTransitionTimeout() {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             final DisplayContent dc = mDisplayContent;
             if (dc == null) {
                 return;
diff --git a/services/core/java/com/android/server/am/AppWarnings.java b/services/core/java/com/android/server/wm/AppWarnings.java
similarity index 99%
rename from services/core/java/com/android/server/am/AppWarnings.java
rename to services/core/java/com/android/server/wm/AppWarnings.java
index a705180..0436857 100644
--- a/services/core/java/com/android/server/am/AppWarnings.java
+++ b/services/core/java/com/android/server/wm/AppWarnings.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.annotation.UiThread;
 import android.content.ComponentName;
diff --git a/services/core/java/com/android/server/wm/AppWindowContainerController.java b/services/core/java/com/android/server/wm/AppWindowContainerController.java
index 7435ea5..584c1e4 100644
--- a/services/core/java/com/android/server/wm/AppWindowContainerController.java
+++ b/services/core/java/com/android/server/wm/AppWindowContainerController.java
@@ -135,7 +135,7 @@
             final StartingData startingData;
             final AppWindowToken container;
 
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 if (mContainer == null) {
                     if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "mContainer was null while trying to"
                             + " add starting window");
@@ -169,7 +169,7 @@
             }
             if (surface != null) {
                 boolean abort = false;
-                synchronized (mWindowMap) {
+                synchronized (mGlobalLock) {
                     // If the window was successfully added, then
                     // we need to remove it.
                     if (container.removed || container.startingData == null) {
@@ -219,7 +219,7 @@
         super(listener, service);
         mHandler = new H(service.mH.getLooper());
         mToken = token;
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             AppWindowToken atoken = mRoot.getAppWindowToken(mToken.asBinder());
             if (atoken != null) {
                 // TODO: Should this throw an exception instead?
@@ -256,7 +256,7 @@
     }
 
     public void removeContainer(int displayId) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent dc = mRoot.getDisplayContent(displayId);
             if (dc == null) {
                 Slog.w(TAG_WM, "removeAppToken: Attempted to remove binder token: "
@@ -274,7 +274,7 @@
     }
 
     public void reparent(TaskWindowContainerController taskController, int position) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (DEBUG_ADD_REMOVE) Slog.i(TAG_WM, "reparent: moving app token=" + mToken
                     + " to task=" + taskController + " at " + position);
             if (mContainer == null) {
@@ -294,7 +294,7 @@
 
     public Configuration setOrientation(int requestedOrientation, int displayId,
             Configuration displayConfig, boolean freezeScreenIfNeeded) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM,
                         "Attempted to set orientation of non-existing app token: " + mToken);
@@ -310,7 +310,7 @@
     }
 
     public int getOrientation() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 return SCREEN_ORIENTATION_UNSPECIFIED;
             }
@@ -320,7 +320,7 @@
     }
 
     public void setDisablePreviewScreenshots(boolean disable) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM, "Attempted to set disable screenshots of non-existing app"
                         + " token: " + mToken);
@@ -331,7 +331,7 @@
     }
 
     public void setVisibility(boolean visible, boolean deferHidingClient) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM, "Attempted to set visibility of non-existing app token: "
                         + mToken);
@@ -449,7 +449,7 @@
      * of Keyguard flags it's going to set on its windows.
      */
     public void notifyUnknownVisibilityLaunched() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer != null) {
                 mContainer.getDisplayContent().mUnknownAppVisibilityController.notifyLaunched(
                         mContainer);
@@ -461,7 +461,7 @@
             CharSequence nonLocalizedLabel, int labelRes, int icon, int logo, int windowFlags,
             IBinder transferFrom, boolean newTask, boolean taskSwitch, boolean processRunning,
             boolean allowTaskSnapshot, boolean activityCreated, boolean fromRecents) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (DEBUG_STARTING_WINDOW) Slog.v(TAG_WM, "setAppStartingWindow: token=" + mToken
                     + " pkg=" + pkg + " transferFrom=" + transferFrom + " newTask=" + newTask
                     + " taskSwitch=" + taskSwitch + " processRunning=" + processRunning
@@ -611,7 +611,7 @@
     }
 
     public void removeStartingWindow() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer.startingWindow == null) {
                 if (mContainer.startingData != null) {
                     // Starting window has not been added yet, but it is scheduled to be added.
@@ -664,7 +664,7 @@
     }
 
     public void pauseKeyDispatching() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer != null) {
                 mContainer.getDisplayContent().getInputMonitor().pauseDispatchingLw(mContainer);
             }
@@ -672,7 +672,7 @@
     }
 
     public void resumeKeyDispatching() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer != null) {
                 mContainer.getDisplayContent().getInputMonitor().resumeDispatchingLw(mContainer);
             }
@@ -680,7 +680,7 @@
     }
 
     public void notifyAppResumed(boolean wasStopped) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM, "Attempted to notify resumed of non-existing app token: " + mToken);
                 return;
@@ -690,7 +690,7 @@
     }
 
     public void notifyAppStopping() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM, "Attempted to notify stopping on non-existing app token: "
                         + mToken);
@@ -701,7 +701,7 @@
     }
 
     public void notifyAppStopped() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM, "Attempted to notify stopped of non-existing app token: "
                         + mToken);
@@ -712,7 +712,7 @@
     }
 
     public void startFreezingScreen(int configChanges) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM,
                         "Attempted to freeze screen with non-existing app token: " + mContainer);
@@ -729,7 +729,7 @@
     }
 
     public void stopFreezingScreen(boolean force) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 return;
             }
@@ -740,7 +740,7 @@
     }
 
     public void registerRemoteAnimations(RemoteAnimationDefinition definition) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM, "Attempted to register remote animations with non-existing app"
                         + " token: " + mToken);
@@ -775,7 +775,7 @@
      * Apply override app transition base on options & animation type.
      */
     public void applyOptionsLocked(ActivityOptions pendingOptions, Intent intent) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final int animationType = pendingOptions.getAnimationType();
             final DisplayContent displayContent = mContainer.getDisplayContent();
             switch (animationType) {
@@ -875,7 +875,7 @@
      * signal on the WM side.
      */
     public void setWillCloseOrEnterPip(boolean willCloseOrEnterPip) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 return;
             }
diff --git a/services/core/java/com/android/server/am/AssistDataReceiverProxy.java b/services/core/java/com/android/server/wm/AssistDataReceiverProxy.java
similarity index 92%
rename from services/core/java/com/android/server/am/AssistDataReceiverProxy.java
rename to services/core/java/com/android/server/wm/AssistDataReceiverProxy.java
index 9991ce1..6756273 100644
--- a/services/core/java/com/android/server/am/AssistDataReceiverProxy.java
+++ b/services/core/java/com/android/server/wm/AssistDataReceiverProxy.java
@@ -14,10 +14,10 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
-import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
-import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
 
 import android.app.IAssistDataReceiver;
 import android.graphics.Bitmap;
@@ -34,7 +34,7 @@
 class AssistDataReceiverProxy implements AssistDataRequesterCallbacks,
         Binder.DeathRecipient {
 
-    private static final String TAG = TAG_WITH_CLASS_NAME ? "AssistDataReceiverProxy" : TAG_AM;
+    private static final String TAG = TAG_WITH_CLASS_NAME ? "AssistDataReceiverProxy" : TAG_ATM;
 
     private String mCallerPackage;
     private IAssistDataReceiver mReceiver;
diff --git a/services/core/java/com/android/server/am/ClientLifecycleManager.java b/services/core/java/com/android/server/wm/ClientLifecycleManager.java
similarity index 99%
rename from services/core/java/com/android/server/am/ClientLifecycleManager.java
rename to services/core/java/com/android/server/wm/ClientLifecycleManager.java
index ae8d9fc..7430f0f 100644
--- a/services/core/java/com/android/server/am/ClientLifecycleManager.java
+++ b/services/core/java/com/android/server/wm/ClientLifecycleManager.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.annotation.NonNull;
 import android.app.IApplicationThread;
diff --git a/services/core/java/com/android/server/am/CompatModePackages.java b/services/core/java/com/android/server/wm/CompatModePackages.java
similarity index 97%
rename from services/core/java/com/android/server/am/CompatModePackages.java
rename to services/core/java/com/android/server/wm/CompatModePackages.java
index 3c4ab00..c8f8e82 100644
--- a/services/core/java/com/android/server/am/CompatModePackages.java
+++ b/services/core/java/com/android/server/wm/CompatModePackages.java
@@ -14,13 +14,13 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
-import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
 
 import java.io.File;
 import java.io.FileInputStream;
diff --git a/services/core/java/com/android/server/am/DeprecatedTargetSdkVersionDialog.java b/services/core/java/com/android/server/wm/DeprecatedTargetSdkVersionDialog.java
similarity index 94%
rename from services/core/java/com/android/server/am/DeprecatedTargetSdkVersionDialog.java
rename to services/core/java/com/android/server/wm/DeprecatedTargetSdkVersionDialog.java
index b39873f..37244bd 100644
--- a/services/core/java/com/android/server/am/DeprecatedTargetSdkVersionDialog.java
+++ b/services/core/java/com/android/server/wm/DeprecatedTargetSdkVersionDialog.java
@@ -14,10 +14,10 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
 
 import android.app.AlertDialog;
 import android.content.Context;
@@ -25,7 +25,6 @@
 import android.content.pm.ApplicationInfo;
 import android.content.pm.PackageItemInfo;
 import android.content.pm.PackageManager;
-import android.os.SystemPropertiesProto;
 import android.util.Log;
 import android.view.Window;
 import android.view.WindowManager;
diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java
index ba03034..348b2af 100644
--- a/services/core/java/com/android/server/wm/DisplayContent.java
+++ b/services/core/java/com/android/server/wm/DisplayContent.java
@@ -314,7 +314,7 @@
      * Last applied orientation of the display.
      * Constants as per {@link android.content.pm.ActivityInfo.ScreenOrientation}.
      *
-     * @see WindowManagerService#updateOrientationFromAppTokensLocked(boolean, int)
+     * @see #updateOrientationFromAppTokens()
      */
     private int mLastOrientation = SCREEN_ORIENTATION_UNSPECIFIED;
 
@@ -1045,18 +1045,10 @@
         return mLastOrientation;
     }
 
-    void setLastOrientation(int orientation) {
-        mLastOrientation = orientation;
-    }
-
     boolean getAltOrientation() {
         return mAltOrientation;
     }
 
-    void setAltOrientation(boolean altOrientation) {
-        mAltOrientation = altOrientation;
-    }
-
     int getLastWindowForcedOrientation() {
         return mLastWindowForcedOrientation;
     }
@@ -1109,6 +1101,34 @@
         return true;
     }
 
+    /** Notify the configuration change of this display. */
+    void sendNewConfiguration() {
+        mService.mH.obtainMessage(SEND_NEW_CONFIGURATION, this).sendToTarget();
+    }
+
+    /**
+     * Determine the new desired orientation of this display.
+     *
+     * The orientation is computed from non-application windows first. If none of the
+     * non-application windows specify orientation, the orientation is computed from application
+     * tokens.
+     *
+     * @return {@code true} if the orientation is changed.
+     */
+    boolean updateOrientationFromAppTokens() {
+        return updateOrientationFromAppTokens(false /* forceUpdate */);
+    }
+
+    boolean updateOrientationFromAppTokens(boolean forceUpdate) {
+        final int req = getOrientation();
+        if (req != mLastOrientation || forceUpdate) {
+            mLastOrientation = req;
+            mDisplayRotation.setCurrentOrientation(req);
+            return updateRotationUnchecked(forceUpdate);
+        }
+        return false;
+    }
+
     /**
      * Update rotation of the display and send configuration if the rotation is changed.
      *
@@ -1117,7 +1137,7 @@
     boolean updateRotationAndSendNewConfigIfNeeded() {
         final boolean changed = updateRotationUnchecked(false /* forceUpdate */);
         if (changed) {
-            mService.mH.obtainMessage(SEND_NEW_CONFIGURATION, mDisplayId).sendToTarget();
+            sendNewConfiguration();
         }
         return changed;
     }
@@ -2343,6 +2363,7 @@
             mWindowingLayer.release();
             mOverlayLayer.release();
         } finally {
+            mDisplayReady = false;
             mRemovingDisplay = false;
         }
 
@@ -3348,9 +3369,9 @@
 
             if ((pendingLayoutChanges & FINISH_LAYOUT_REDO_CONFIG) != 0) {
                 if (DEBUG_LAYOUT) Slog.v(TAG, "Computing new config from layout");
-                if (mService.updateOrientationFromAppTokensLocked(mDisplayId)) {
+                if (updateOrientationFromAppTokens()) {
                     setLayoutNeeded();
-                    mService.mH.obtainMessage(SEND_NEW_CONFIGURATION, mDisplayId).sendToTarget();
+                    sendNewConfiguration();
                 }
             }
 
diff --git a/services/core/java/com/android/server/wm/DisplayWindowController.java b/services/core/java/com/android/server/wm/DisplayWindowController.java
index 01d556a..f772216 100644
--- a/services/core/java/com/android/server/wm/DisplayWindowController.java
+++ b/services/core/java/com/android/server/wm/DisplayWindowController.java
@@ -52,7 +52,7 @@
         super(listener, WindowManagerService.getInstance());
         mDisplayId = display.getDisplayId();
 
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final long callingIdentity = Binder.clearCallingIdentity();
             try {
                 mRoot.createDisplayContent(display, this /* controller */);
@@ -75,7 +75,7 @@
 
     @Override
     public void removeContainer() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if(mContainer == null) {
                 if (DEBUG_DISPLAY) Slog.i(TAG_WM, "removeDisplay: could not find displayId="
                         + mDisplayId);
@@ -102,7 +102,7 @@
      * {@link android.hardware.display.DisplayManager.DisplayListener#onDisplayChanged(int)}.
      */
     public void onDisplayChanged() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 if (DEBUG_DISPLAY) Slog.i(TAG_WM, "onDisplayChanged: could not find display="
                         + mDisplayId);
@@ -118,7 +118,7 @@
      */
     public void positionChildAt(StackWindowController child, int position,
             boolean includingParents) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (DEBUG_STACK) Slog.i(TAG_WM, "positionTaskStackAt: positioning stack=" + child
                     + " at " + position);
             if (mContainer == null) {
@@ -140,7 +140,7 @@
      * attempt to update the IME target before all information about the Windows have been updated.
      */
     public void deferUpdateImeTarget() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent dc = mRoot.getDisplayContent(mDisplayId);
             if (dc != null) {
                 dc.deferUpdateImeTarget();
@@ -152,7 +152,7 @@
      * Resumes updating the IME target after deferring. See {@link #deferUpdateImeTarget()}
      */
     public void continueUpdateImeTarget() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent dc = mRoot.getDisplayContent(mDisplayId);
             if (dc != null) {
                 dc.continueUpdateImeTarget();
@@ -167,7 +167,7 @@
      * @param moveFocusNow Specifies if we should update the focused window immediately.
      */
     public void setFocusedApp(IBinder token, boolean moveFocusNow) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 if (DEBUG_FOCUS_LIGHT) Slog.i(TAG_WM, "setFocusedApp: could not find displayId="
                         + mDisplayId);
@@ -213,21 +213,21 @@
     public void prepareAppTransition(@WindowManager.TransitionType int transit,
             boolean alwaysKeepCurrent, @WindowManager.TransitionFlags int flags,
             boolean forceOverride) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.getDisplayContent(mDisplayId).prepareAppTransition(transit, alwaysKeepCurrent,
                     flags, forceOverride);
         }
     }
 
     public void executeAppTransition() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.getDisplayContent(mDisplayId).executeAppTransition();
         }
     }
 
     public void overridePendingAppTransition(String packageName,
             int enterAnim, int exitAnim, IRemoteCallback startedCallback) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.getDisplayContent(mDisplayId).mAppTransition.overridePendingAppTransition(
                     packageName, enterAnim, exitAnim, startedCallback);
         }
@@ -235,7 +235,7 @@
 
     public void overridePendingAppTransitionScaleUp(int startX, int startY, int startWidth,
             int startHeight) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.getDisplayContent(mDisplayId).mAppTransition.overridePendingAppTransitionScaleUp(
                     startX, startY, startWidth, startHeight);
         }
@@ -243,7 +243,7 @@
 
     public void overridePendingAppTransitionClipReveal(int startX, int startY,
             int startWidth, int startHeight) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.getDisplayContent(mDisplayId)
                     .mAppTransition.overridePendingAppTransitionClipReveal(startX, startY,
                     startWidth, startHeight);
@@ -252,7 +252,7 @@
 
     public void overridePendingAppTransitionThumb(GraphicBuffer srcThumb, int startX,
             int startY, IRemoteCallback startedCallback, boolean scaleUp) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.getDisplayContent(mDisplayId)
                     .mAppTransition.overridePendingAppTransitionThumb(srcThumb, startX, startY,
                     startedCallback, scaleUp);
@@ -262,7 +262,7 @@
     public void overridePendingAppTransitionAspectScaledThumb(GraphicBuffer srcThumb, int startX,
             int startY, int targetWidth, int targetHeight, IRemoteCallback startedCallback,
             boolean scaleUp) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.getDisplayContent(mDisplayId)
                     .mAppTransition.overridePendingAppTransitionAspectScaledThumb(srcThumb, startX,
                     startY, targetWidth, targetHeight, startedCallback, scaleUp);
@@ -272,7 +272,7 @@
     public void overridePendingAppTransitionMultiThumb(AppTransitionAnimationSpec[] specs,
             IRemoteCallback onAnimationStartedCallback, IRemoteCallback onAnimationFinishedCallback,
             boolean scaleUp) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.getDisplayContent(mDisplayId)
                     .mAppTransition.overridePendingAppTransitionMultiThumb(specs,
                     onAnimationStartedCallback, onAnimationFinishedCallback, scaleUp);
@@ -280,14 +280,14 @@
     }
 
     public void overridePendingAppTransitionStartCrossProfileApps() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.getDisplayContent(mDisplayId)
                     .mAppTransition.overridePendingAppTransitionStartCrossProfileApps();
         }
     }
 
     public void overridePendingAppTransitionInPlace(String packageName, int anim) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.getDisplayContent(mDisplayId)
                     .mAppTransition.overrideInPlaceAppTransition(packageName, anim);
         }
@@ -299,7 +299,7 @@
      * @return The pending app transition of the display.
      */
     public @TransitionType int getPendingAppTransition() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return mRoot.getDisplayContent(mDisplayId).mAppTransition.getAppTransition();
         }
     }
diff --git a/services/core/java/com/android/server/wm/DockedStackDividerController.java b/services/core/java/com/android/server/wm/DockedStackDividerController.java
index 8ed29a9..985ce06 100644
--- a/services/core/java/com/android/server/wm/DockedStackDividerController.java
+++ b/services/core/java/com/android/server/wm/DockedStackDividerController.java
@@ -27,14 +27,15 @@
 import static android.view.WindowManager.DOCKED_LEFT;
 import static android.view.WindowManager.DOCKED_RIGHT;
 import static android.view.WindowManager.DOCKED_TOP;
+import static android.view.WindowManager.TRANSIT_NONE;
+
 import static com.android.server.wm.AppTransition.DEFAULT_APP_TRANSITION_DURATION;
 import static com.android.server.wm.AppTransition.TOUCH_RESPONSE_INTERPOLATOR;
-import static android.view.WindowManager.TRANSIT_NONE;
+import static com.android.server.wm.DockedStackDividerControllerProto.MINIMIZED_DOCK;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.WindowManagerService.H.NOTIFY_DOCKED_STACK_MINIMIZED_CHANGED;
 import static com.android.server.wm.WindowManagerService.LAYER_OFFSET_DIM;
-import static com.android.server.wm.DockedStackDividerControllerProto.MINIMIZED_DOCK;
 
 import android.content.Context;
 import android.content.res.Configuration;
@@ -820,7 +821,7 @@
                 mService.mWaitingForDrawnCallback.run();
             }
             mService.mWaitingForDrawnCallback = () -> {
-                synchronized (mService.mWindowMap) {
+                synchronized (mService.mGlobalLock) {
                     mAnimationStartDelayed = false;
                     if (mDelayedImeWin != null) {
                         mDelayedImeWin.endDelayingAnimationStart();
diff --git a/services/core/java/com/android/server/wm/DragDropController.java b/services/core/java/com/android/server/wm/DragDropController.java
index f42e979..ce8c979 100644
--- a/services/core/java/com/android/server/wm/DragDropController.java
+++ b/services/core/java/com/android/server/wm/DragDropController.java
@@ -104,7 +104,7 @@
         final boolean callbackResult = mCallback.get().prePerformDrag(window, dragToken,
                 touchSource, touchX, touchY, thumbCenterX, thumbCenterY, data);
         try {
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 try {
                     if (!callbackResult) {
                         Slog.w(TAG_WM, "IDragDropCallback rejects the performDrag request");
@@ -209,7 +209,7 @@
 
         mCallback.get().preReportDropResult(window, consumed);
         try {
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 if (mDragState == null) {
                     // Most likely the drop recipient ANRed and we ended the drag
                     // out from under it.  Log the issue and move on.
@@ -248,7 +248,7 @@
 
         mCallback.get().preCancelDragAndDrop(dragToken);
         try {
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 if (mDragState == null) {
                     Slog.w(TAG_WM, "cancelDragAndDrop() without prepareDrag()");
                     throw new IllegalStateException("cancelDragAndDrop() without prepareDrag()");
@@ -277,7 +277,7 @@
      * @param newY Y coordinate value in dp in the screen coordinate
      */
     void handleMotionEvent(boolean keepHandling, float newX, float newY) {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             if (!dragDropActiveLocked()) {
                 // The drag has ended but the clean-up message has not been processed by
                 // window manager. Drop events that occur after this until window manager
@@ -352,7 +352,7 @@
                         Slog.w(TAG_WM, "Timeout ending drag to win " + win);
                     }
 
-                    synchronized (mService.mWindowMap) {
+                    synchronized (mService.mGlobalLock) {
                         // !!! TODO: ANR the drag-receiving app
                         if (mDragState != null) {
                             mDragState.mDragResult = false;
@@ -368,14 +368,14 @@
                     final DragState.InputInterceptor interceptor =
                             (DragState.InputInterceptor) msg.obj;
                     if (interceptor == null) return;
-                    synchronized (mService.mWindowMap) {
+                    synchronized (mService.mGlobalLock) {
                         interceptor.tearDown();
                     }
                     break;
                 }
 
                 case MSG_ANIMATION_END: {
-                    synchronized (mService.mWindowMap) {
+                    synchronized (mService.mGlobalLock) {
                         if (mDragState == null) {
                             Slog.wtf(TAG_WM, "mDragState unexpectedly became null while " +
                                     "plyaing animation");
diff --git a/services/core/java/com/android/server/am/FactoryErrorDialog.java b/services/core/java/com/android/server/wm/FactoryErrorDialog.java
similarity index 95%
rename from services/core/java/com/android/server/am/FactoryErrorDialog.java
rename to services/core/java/com/android/server/wm/FactoryErrorDialog.java
index f4632c1..88b5475 100644
--- a/services/core/java/com/android/server/am/FactoryErrorDialog.java
+++ b/services/core/java/com/android/server/wm/FactoryErrorDialog.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.content.Context;
 import android.content.DialogInterface;
@@ -22,6 +22,8 @@
 import android.os.Message;
 import android.view.WindowManager;
 
+import com.android.server.am.BaseErrorDialog;
+
 final class FactoryErrorDialog extends BaseErrorDialog {
     public FactoryErrorDialog(Context context, CharSequence msg) {
         super(context);
diff --git a/services/core/java/com/android/server/wm/InputManagerCallback.java b/services/core/java/com/android/server/wm/InputManagerCallback.java
index 10d77e5..f823caa 100644
--- a/services/core/java/com/android/server/wm/InputManagerCallback.java
+++ b/services/core/java/com/android/server/wm/InputManagerCallback.java
@@ -53,7 +53,7 @@
             return;
         }
 
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             WindowState windowState = (WindowState) inputWindowHandle.windowState;
             if (windowState != null) {
                 Slog.i(TAG_WM, "WINDOW DIED " + windowState);
@@ -74,7 +74,7 @@
         AppWindowToken appWindowToken = null;
         WindowState windowState = null;
         boolean aboveSystem = false;
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             if (inputWindowHandle != null) {
                 windowState = (WindowState) inputWindowHandle.windowState;
                 if (windowState != null) {
diff --git a/services/core/java/com/android/server/wm/InputMonitor.java b/services/core/java/com/android/server/wm/InputMonitor.java
index ed3e6c6..0e4ab53 100644
--- a/services/core/java/com/android/server/wm/InputMonitor.java
+++ b/services/core/java/com/android/server/wm/InputMonitor.java
@@ -96,7 +96,7 @@
 
         @Override
         public void dismiss() {
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 if (mInputMonitor.destroyInputConsumer(mWindowHandle.name)) {
                     mInputEventReceiver.dispose();
                 }
diff --git a/services/core/java/com/android/server/am/KeyguardController.java b/services/core/java/com/android/server/wm/KeyguardController.java
similarity index 98%
rename from services/core/java/com/android/server/am/KeyguardController.java
rename to services/core/java/com/android/server/wm/KeyguardController.java
index 9c41c77..3560635 100644
--- a/services/core/java/com/android/server/am/KeyguardController.java
+++ b/services/core/java/com/android/server/wm/KeyguardController.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
 import static android.view.Display.DEFAULT_DISPLAY;
@@ -30,9 +30,9 @@
 import static android.view.WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_TO_SHADE;
 import static android.view.WindowManagerPolicyConstants.KEYGUARD_GOING_AWAY_FLAG_WITH_WALLPAPER;
 
-import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.am.KeyguardControllerProto.KEYGUARD_OCCLUDED_STATES;
 import static com.android.server.am.KeyguardControllerProto.KEYGUARD_SHOWING;
 import static com.android.server.am.KeyguardOccludedProto.DISPLAY_ID;
@@ -48,8 +48,6 @@
 import com.android.internal.policy.IKeyguardDismissCallback;
 import com.android.server.policy.WindowManagerPolicy;
 import com.android.server.wm.ActivityTaskManagerInternal.SleepToken;
-import com.android.server.wm.DisplayWindowController;
-import com.android.server.wm.WindowManagerService;
 
 import java.io.PrintWriter;
 
diff --git a/services/core/java/com/android/server/am/LaunchParamsController.java b/services/core/java/com/android/server/wm/LaunchParamsController.java
similarity index 97%
rename from services/core/java/com/android/server/am/LaunchParamsController.java
rename to services/core/java/com/android/server/wm/LaunchParamsController.java
index 68e897f..252f47c 100644
--- a/services/core/java/com/android/server/am/LaunchParamsController.java
+++ b/services/core/java/com/android/server/wm/LaunchParamsController.java
@@ -14,15 +14,15 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
 import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.Display.INVALID_DISPLAY;
 
-import static com.android.server.am.LaunchParamsController.LaunchParamsModifier.RESULT_CONTINUE;
-import static com.android.server.am.LaunchParamsController.LaunchParamsModifier.RESULT_DONE;
-import static com.android.server.am.LaunchParamsController.LaunchParamsModifier.RESULT_SKIP;
+import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_CONTINUE;
+import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_DONE;
+import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_SKIP;
 
 import android.annotation.IntDef;
 import android.app.ActivityOptions;
diff --git a/services/core/java/com/android/server/am/LaunchWarningWindow.java b/services/core/java/com/android/server/wm/LaunchWarningWindow.java
similarity index 98%
rename from services/core/java/com/android/server/am/LaunchWarningWindow.java
rename to services/core/java/com/android/server/wm/LaunchWarningWindow.java
index 30c3066..1c0093e 100644
--- a/services/core/java/com/android/server/am/LaunchWarningWindow.java
+++ b/services/core/java/com/android/server/wm/LaunchWarningWindow.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import com.android.internal.R;
 
diff --git a/services/core/java/com/android/server/am/LockTaskController.java b/services/core/java/com/android/server/wm/LockTaskController.java
similarity index 97%
rename from services/core/java/com/android/server/am/LockTaskController.java
rename to services/core/java/com/android/server/wm/LockTaskController.java
index bcebaaa..41d0777 100644
--- a/services/core/java/com/android/server/am/LockTaskController.java
+++ b/services/core/java/com/android/server/wm/LockTaskController.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
@@ -28,15 +28,15 @@
 import static android.telecom.TelecomManager.EMERGENCY_DIALER_COMPONENT;
 import static android.view.Display.DEFAULT_DISPLAY;
 
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
-import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
-import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
-import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
-import static com.android.server.am.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_DONT_LOCK;
+import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE;
+import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_LAUNCHABLE_PRIV;
+import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_PINNABLE;
+import static com.android.server.wm.TaskRecord.LOCK_TASK_AUTH_WHITELISTED;
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -66,8 +66,8 @@
 import com.android.internal.statusbar.IStatusBarService;
 import com.android.internal.widget.LockPatternUtils;
 import com.android.server.LocalServices;
+import com.android.server.am.ActivityManagerService;
 import com.android.server.statusbar.StatusBarManagerInternal;
-import com.android.server.wm.WindowManagerService;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
@@ -412,7 +412,7 @@
     /**
      * Clear all locked tasks and request the end of LockTask mode.
      *
-     * This method is called by {@link UserController} when starting a new foreground user, and,
+     * This method is called by UserController when starting a new foreground user, and,
      * unlike {@link #stopLockTaskMode(TaskRecord, boolean, int)}, it doesn't perform the checks.
      */
     void clearLockedTasks(String reason) {
diff --git a/services/core/java/com/android/server/am/PendingRemoteAnimationRegistry.java b/services/core/java/com/android/server/wm/PendingRemoteAnimationRegistry.java
similarity index 96%
rename from services/core/java/com/android/server/am/PendingRemoteAnimationRegistry.java
rename to services/core/java/com/android/server/wm/PendingRemoteAnimationRegistry.java
index 877d896..dcb9a6a 100644
--- a/services/core/java/com/android/server/am/PendingRemoteAnimationRegistry.java
+++ b/services/core/java/com/android/server/wm/PendingRemoteAnimationRegistry.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.annotation.Nullable;
 import android.app.ActivityOptions;
@@ -22,6 +22,8 @@
 import android.util.ArrayMap;
 import android.view.RemoteAnimationAdapter;
 
+import com.android.server.am.ActivityManagerService;
+
 /**
  * Registry to keep track of remote animations to be run for activity starts from a certain package.
  *
diff --git a/services/core/java/com/android/server/am/PersisterQueue.java b/services/core/java/com/android/server/wm/PersisterQueue.java
similarity index 98%
rename from services/core/java/com/android/server/am/PersisterQueue.java
rename to services/core/java/com/android/server/wm/PersisterQueue.java
index 60ea0fa..1cfc7ac 100644
--- a/services/core/java/com/android/server/am/PersisterQueue.java
+++ b/services/core/java/com/android/server/wm/PersisterQueue.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.os.Process;
 import android.os.SystemClock;
@@ -171,6 +171,11 @@
         mListeners.add(listener);
     }
 
+    @VisibleForTesting
+    boolean removeListener(Listener listener) {
+        return mListeners.remove(listener);
+    }
+
     private void processNextItem() throws InterruptedException {
         // This part is extracted into a method so that the GC can clearly see the end of the
         // scope of the variable 'item'.  If this part was in the loop in LazyTaskWriterThread, the
diff --git a/services/core/java/com/android/server/am/PinnedActivityStack.java b/services/core/java/com/android/server/wm/PinnedActivityStack.java
similarity index 96%
rename from services/core/java/com/android/server/am/PinnedActivityStack.java
rename to services/core/java/com/android/server/wm/PinnedActivityStack.java
index edc6e53..af18077 100644
--- a/services/core/java/com/android/server/am/PinnedActivityStack.java
+++ b/services/core/java/com/android/server/wm/PinnedActivityStack.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
@@ -23,9 +23,6 @@
 import android.content.res.Configuration;
 import android.graphics.Rect;
 
-import com.android.server.wm.PinnedStackWindowController;
-import com.android.server.wm.PinnedStackWindowListener;
-
 import java.util.ArrayList;
 import java.util.List;
 
diff --git a/services/core/java/com/android/server/wm/PinnedStackController.java b/services/core/java/com/android/server/wm/PinnedStackController.java
index b64d4f8..405aaab 100644
--- a/services/core/java/com/android/server/wm/PinnedStackController.java
+++ b/services/core/java/com/android/server/wm/PinnedStackController.java
@@ -20,10 +20,10 @@
 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
 import static android.util.TypedValue.COMPLEX_UNIT_DIP;
 
-import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 import static com.android.server.wm.PinnedStackControllerProto.DEFAULT_BOUNDS;
 import static com.android.server.wm.PinnedStackControllerProto.MOVEMENT_BOUNDS;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
 
 import android.app.RemoteAction;
 import android.content.pm.ParceledListSlice;
@@ -142,7 +142,7 @@
 
         @Override
         public int getDisplayRotation() {
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 return mDisplayInfo.rotation;
             }
         }
@@ -288,7 +288,7 @@
      * will apply the default bounds to the provided snap fraction.
      */
     Rect getDefaultBounds(float snapFraction) {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             final Rect insetBounds = new Rect();
             getInsetBounds(insetBounds);
 
@@ -324,7 +324,7 @@
      * new orientation of the device if necessary.
      */
     boolean onTaskStackBoundsChanged(Rect targetBounds, Rect outBounds) {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             final DisplayInfo displayInfo = mDisplayContent.getDisplayInfo();
             if (mDisplayInfo.equals(displayInfo)) {
                 // We are already in the right orientation, ignore
@@ -481,7 +481,7 @@
      */
     private void notifyMovementBoundsChanged(boolean fromImeAdjustment,
             boolean fromShelfAdjustment) {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             if (mPinnedStackListener == null) {
                 return;
             }
@@ -513,7 +513,7 @@
      * @return the bounds on the screen that the PIP can be visible in.
      */
     private void getInsetBounds(Rect outRect) {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             mService.mPolicy.getStableInsetsLw(mDisplayInfo.rotation, mDisplayInfo.logicalWidth,
                     mDisplayInfo.logicalHeight, mDisplayInfo.displayCutout, mTmpInsets);
             outRect.set(mTmpInsets.left + mScreenEdgeInsets.x, mTmpInsets.top + mScreenEdgeInsets.y,
@@ -527,7 +527,7 @@
      *         controller.
      */
     private Rect getMovementBounds(Rect stackBounds) {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             return getMovementBounds(stackBounds, true /* adjustForIme */,
                     true /* adjustForShelf */);
         }
@@ -538,7 +538,7 @@
      *         controller.
      */
     private Rect getMovementBounds(Rect stackBounds, boolean adjustForIme, boolean adjustForShelf) {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             final Rect movementBounds = new Rect();
             getInsetBounds(movementBounds);
 
@@ -554,7 +554,7 @@
      * Applies the minimized offsets to the given stack bounds.
      */
     private void applyMinimizedOffset(Rect stackBounds, Rect movementBounds) {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             mTmpDisplaySize.set(mDisplayInfo.logicalWidth, mDisplayInfo.logicalHeight);
             mService.getStableInsetsLocked(mDisplayContent.getDisplayId(), mStableInsets);
             mSnapAlgorithm.applyMinimizedOffset(stackBounds, movementBounds, mTmpDisplaySize,
diff --git a/services/core/java/com/android/server/wm/PinnedStackWindowController.java b/services/core/java/com/android/server/wm/PinnedStackWindowController.java
index 1807eeb..bbdcc62 100644
--- a/services/core/java/com/android/server/wm/PinnedStackWindowController.java
+++ b/services/core/java/com/android/server/wm/PinnedStackWindowController.java
@@ -47,7 +47,7 @@
      *         default bounds.
      */
     public Rect getPictureInPictureBounds(float aspectRatio, Rect stackBounds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (!mService.mSupportsPictureInPicture || mContainer == null) {
                 return null;
             }
@@ -78,7 +78,7 @@
      */
     public void animateResizePinnedStack(Rect toBounds, Rect sourceHintBounds,
             int animationDuration, boolean fromFullscreen) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 throw new IllegalArgumentException("Pinned stack container not found :(");
             }
@@ -133,7 +133,7 @@
      * Sets the current picture-in-picture aspect ratio.
      */
     public void setPictureInPictureAspectRatio(float aspectRatio) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (!mService.mSupportsPictureInPicture || mContainer == null) {
                 return;
             }
@@ -160,7 +160,7 @@
      * Sets the current picture-in-picture actions.
      */
     public void setPictureInPictureActions(List<RemoteAction> actions) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (!mService.mSupportsPictureInPicture || mContainer == null) {
                 return;
             }
@@ -174,7 +174,7 @@
      * from fullscreen to non-fullscreen bounds.
      */
     public boolean deferScheduleMultiWindowModeChanged() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return mContainer.deferScheduleMultiWindowModeChanged();
         }
     }
@@ -183,7 +183,7 @@
      * @return whether the bounds are currently animating to fullscreen.
      */
     public boolean isAnimatingBoundsToFullscreen() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return mContainer.isAnimatingBoundsToFullscreen();
         }
     }
@@ -192,7 +192,7 @@
      * @return whether the stack can be resized from the bounds animation.
      */
     public boolean pinnedStackResizeDisallowed() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return mContainer.pinnedStackResizeDisallowed();
         }
     }
diff --git a/services/core/java/com/android/server/am/RecentTasks.java b/services/core/java/com/android/server/wm/RecentTasks.java
similarity index 98%
rename from services/core/java/com/android/server/am/RecentTasks.java
rename to services/core/java/com/android/server/wm/RecentTasks.java
index 57f939f..c995d3f 100644
--- a/services/core/java/com/android/server/am/RecentTasks.java
+++ b/services/core/java/com/android/server/wm/RecentTasks.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.FLAG_AND_UNLOCKED;
 import static android.app.ActivityManager.RECENT_IGNORE_UNAVAILABLE;
@@ -33,14 +33,14 @@
 import static android.os.Process.SYSTEM_UID;
 import static android.view.Display.DEFAULT_DISPLAY;
 
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_RECENTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_RECENTS_TRIM_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.am.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS_TRIM_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS;
 import static android.app.ActivityTaskManager.INVALID_TASK_ID;
 
 import android.app.ActivityManager;
@@ -69,7 +69,8 @@
 import android.util.SparseBooleanArray;
 
 import com.android.internal.annotations.VisibleForTesting;
-import com.android.server.am.TaskRecord.TaskActivitiesReport;
+import com.android.server.am.ActivityManagerService;
+import com.android.server.wm.TaskRecord.TaskActivitiesReport;
 
 import com.google.android.collect.Sets;
 
diff --git a/services/core/java/com/android/server/am/RecentsAnimation.java b/services/core/java/com/android/server/wm/RecentsAnimation.java
similarity index 98%
rename from services/core/java/com/android/server/am/RecentsAnimation.java
rename to services/core/java/com/android/server/wm/RecentsAnimation.java
index 41d488ba..7a1ebf2 100644
--- a/services/core/java/com/android/server/am/RecentsAnimation.java
+++ b/services/core/java/com/android/server/wm/RecentsAnimation.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.START_TASK_TO_FRONT;
 import static android.app.AppOpsManager.OP_ASSIST_STRUCTURE;
@@ -26,7 +26,7 @@
 import static android.content.Intent.FLAG_ACTIVITY_NO_ANIMATION;
 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
 import static android.view.WindowManager.TRANSIT_NONE;
-import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
+import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
 import static com.android.server.wm.RecentsAnimationController.REORDER_KEEP_IN_PLACE;
 import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_ORIGINAL_POSITION;
 import static com.android.server.wm.RecentsAnimationController.REORDER_MOVE_TO_TOP;
@@ -42,10 +42,9 @@
 import android.util.Slog;
 import android.view.IRecentsAnimationRunner;
 
-import com.android.server.wm.DisplayWindowController;
-import com.android.server.wm.RecentsAnimationController;
+import com.android.server.wm.AssistDataReceiverProxy;
+import com.android.server.am.AssistDataRequester;
 import com.android.server.wm.RecentsAnimationController.RecentsAnimationCallbacks;
-import com.android.server.wm.WindowManagerService;
 
 /**
  * Manages the recents animation, including the reordering of the stacks for the transition and
diff --git a/services/core/java/com/android/server/wm/RemoteAnimationController.java b/services/core/java/com/android/server/wm/RemoteAnimationController.java
index 0ec4baf..f5acdcc 100644
--- a/services/core/java/com/android/server/wm/RemoteAnimationController.java
+++ b/services/core/java/com/android/server/wm/RemoteAnimationController.java
@@ -182,7 +182,7 @@
         if (DEBUG_REMOTE_ANIMATIONS) Slog.d(TAG, "onAnimationFinished(): mPendingAnimations="
                 + mPendingAnimations.size());
         mHandler.removeCallbacks(mTimeoutRunnable);
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             unlinkToDeathOfRunner();
             releaseFinishedCallback();
             mService.openSurfaceTransaction();
diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java
index 62078f7..67fe5c4 100644
--- a/services/core/java/com/android/server/wm/RootWindowContainer.java
+++ b/services/core/java/com/android/server/wm/RootWindowContainer.java
@@ -42,7 +42,6 @@
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_KEEP_SCREEN_ON;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
-import static com.android.server.wm.WindowManagerService.H.SEND_NEW_CONFIGURATION;
 import static com.android.server.wm.WindowManagerService.H.WINDOW_FREEZE_TIMEOUT;
 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_NORMAL;
 import static com.android.server.wm.WindowManagerService.UPDATE_FOCUS_PLACING_SURFACES;
@@ -911,10 +910,8 @@
         boolean changed = false;
         for (int i = mChildren.size() - 1; i >= 0; i--) {
             final DisplayContent displayContent = mChildren.get(i);
-            if (displayContent.updateRotationUnchecked()) {
+            if (displayContent.updateRotationAndSendNewConfigIfNeeded()) {
                 changed = true;
-                mService.mH.obtainMessage(SEND_NEW_CONFIGURATION, displayContent.getDisplayId())
-                        .sendToTarget();
             }
         }
         return changed;
diff --git a/services/core/java/com/android/server/wm/RootWindowContainerController.java b/services/core/java/com/android/server/wm/RootWindowContainerController.java
index 93be6e9..1176220 100644
--- a/services/core/java/com/android/server/wm/RootWindowContainerController.java
+++ b/services/core/java/com/android/server/wm/RootWindowContainerController.java
@@ -25,7 +25,7 @@
 
     public RootWindowContainerController(RootWindowContainerListener listener) {
         super(listener, WindowManagerService.getInstance());
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.setController(this);
         }
     }
@@ -39,7 +39,7 @@
 
     /** Move the display to the given position. */
     public void positionChildAt(DisplayWindowController child, int position) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mContainer.positionChildAt(position, child.mContainer);
         }
     }
diff --git a/services/core/java/com/android/server/am/RunningTasks.java b/services/core/java/com/android/server/wm/RunningTasks.java
similarity index 98%
rename from services/core/java/com/android/server/am/RunningTasks.java
rename to services/core/java/com/android/server/wm/RunningTasks.java
index d878f51..34282cd 100644
--- a/services/core/java/com/android/server/am/RunningTasks.java
+++ b/services/core/java/com/android/server/wm/RunningTasks.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.app.ActivityManager.RunningTaskInfo;
 import android.app.WindowConfiguration.ActivityType;
diff --git a/services/core/java/com/android/server/am/SafeActivityOptions.java b/services/core/java/com/android/server/wm/SafeActivityOptions.java
similarity index 96%
rename from services/core/java/com/android/server/am/SafeActivityOptions.java
rename to services/core/java/com/android/server/wm/SafeActivityOptions.java
index 1152165..ac90283 100644
--- a/services/core/java/com/android/server/am/SafeActivityOptions.java
+++ b/services/core/java/com/android/server/wm/SafeActivityOptions.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.Manifest.permission.CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS;
 import static android.Manifest.permission.START_TASKS_FROM_RECENTS;
@@ -22,8 +22,8 @@
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 import static android.view.Display.INVALID_DISPLAY;
 import static android.app.ActivityTaskManager.INVALID_TASK_ID;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
 
 import android.annotation.Nullable;
 import android.app.ActivityOptions;
@@ -62,7 +62,7 @@
      *
      * @param bOptions The {@link ActivityOptions} as {@link Bundle}.
      */
-    static SafeActivityOptions fromBundle(Bundle bOptions) {
+    public static SafeActivityOptions fromBundle(Bundle bOptions) {
         return bOptions != null
                 ? new SafeActivityOptions(ActivityOptions.fromBundle(bOptions))
                 : null;
@@ -75,7 +75,7 @@
      *
      * @param options The options to wrap.
      */
-    SafeActivityOptions(@Nullable ActivityOptions options) {
+    public SafeActivityOptions(@Nullable ActivityOptions options) {
         mOriginalCallingPid = Binder.getCallingPid();
         mOriginalCallingUid = Binder.getCallingUid();
         mOriginalOptions = options;
@@ -86,7 +86,7 @@
      * {@link Binder#getCallingUid}. Thus, calling identity MUST NOT be cleared when calling this
      * method.
      */
-    void setCallerOptions(@Nullable ActivityOptions options) {
+    public void setCallerOptions(@Nullable ActivityOptions options) {
         mRealCallingPid = Binder.getCallingPid();
         mRealCallingUid = Binder.getCallingUid();
         mCallerOptions = options;
diff --git a/services/core/java/com/android/server/wm/Session.java b/services/core/java/com/android/server/wm/Session.java
index acc9c03..b411fad 100644
--- a/services/core/java/com/android/server/wm/Session.java
+++ b/services/core/java/com/android/server/wm/Session.java
@@ -143,7 +143,7 @@
 
     @Override
     public void binderDied() {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             mCallback.asBinder().unlinkToDeath(this, 0);
             mClientDead = true;
             killSessionLocked();
@@ -229,14 +229,14 @@
 
     @Override
     public void setInTouchMode(boolean mode) {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             mService.mInTouchMode = mode;
         }
     }
 
     @Override
     public boolean getInTouchMode() {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             return mService.mInTouchMode;
         }
     }
@@ -244,7 +244,7 @@
     @Override
     public boolean performHapticFeedback(IWindow window, int effectId,
             boolean always) {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             long ident = Binder.clearCallingIdentity();
             try {
                 return mService.mPolicy.performHapticFeedbackLw(
@@ -317,7 +317,7 @@
 
     @Override
     public void setWallpaperPosition(IBinder window, float x, float y, float xStep, float yStep) {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             long ident = Binder.clearCallingIdentity();
             try {
                 mService.mRoot.mWallpaperController.setWindowWallpaperPosition(
@@ -331,14 +331,14 @@
 
     @Override
     public void wallpaperOffsetsComplete(IBinder window) {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             mService.mRoot.mWallpaperController.wallpaperOffsetsComplete(window);
         }
     }
 
     @Override
     public void setWallpaperDisplayOffset(IBinder window, int x, int y) {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             long ident = Binder.clearCallingIdentity();
             try {
                 mService.mRoot.mWallpaperController.setWindowWallpaperDisplayOffset(
@@ -352,7 +352,7 @@
     @Override
     public Bundle sendWallpaperCommand(IBinder window, String action, int x, int y,
             int z, Bundle extras, boolean sync) {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             long ident = Binder.clearCallingIdentity();
             try {
                 return mService.mRoot.mWallpaperController.sendWindowWallpaperCommand(
@@ -366,14 +366,14 @@
 
     @Override
     public void wallpaperCommandComplete(IBinder window, Bundle result) {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             mService.mRoot.mWallpaperController.wallpaperCommandComplete(window);
         }
     }
 
     @Override
     public void onRectangleOnScreenRequested(IBinder token, Rect rectangle) {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             final long identity = Binder.clearCallingIdentity();
             try {
                 mService.onRectangleOnScreenRequested(token, rectangle);
diff --git a/services/core/java/com/android/server/wm/StackWindowController.java b/services/core/java/com/android/server/wm/StackWindowController.java
index 6ac63a1..c920b9e 100644
--- a/services/core/java/com/android/server/wm/StackWindowController.java
+++ b/services/core/java/com/android/server/wm/StackWindowController.java
@@ -16,6 +16,11 @@
 
 package com.android.server.wm;
 
+import static com.android.server.wm.WindowContainer.POSITION_BOTTOM;
+import static com.android.server.wm.WindowContainer.POSITION_TOP;
+import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STACK;
+import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
+
 import android.app.WindowConfiguration;
 import android.content.res.Configuration;
 import android.graphics.Rect;
@@ -31,11 +36,6 @@
 
 import java.lang.ref.WeakReference;
 
-import static com.android.server.wm.WindowContainer.POSITION_BOTTOM;
-import static com.android.server.wm.WindowContainer.POSITION_TOP;
-import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STACK;
-import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
-
 /**
  * Controller for the stack container. This is created by activity manager to link activity stacks
  * to the stack container they use in window manager.
@@ -67,7 +67,7 @@
         mStackId = stackId;
         mHandler = new H(new WeakReference<>(this), service.mH.getLooper());
 
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent dc = mRoot.getDisplayContent(displayId);
             if (dc == null) {
                 throw new IllegalArgumentException("Trying to add stackId=" + stackId
@@ -81,7 +81,7 @@
 
     @Override
     public void removeContainer() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer != null) {
                 mContainer.removeIfPossible();
                 super.removeContainer();
@@ -90,7 +90,7 @@
     }
 
     public void reparent(int displayId, Rect outStackBounds, boolean onTop) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 throw new IllegalArgumentException("Trying to move unknown stackId=" + mStackId
                         + " to displayId=" + displayId);
@@ -108,7 +108,7 @@
     }
 
     public void positionChildAt(TaskWindowContainerController child, int position) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (DEBUG_STACK) Slog.i(TAG_WM, "positionChildAt: positioning task=" + child
                     + " at " + position);
             if (child.mContainer == null) {
@@ -132,7 +132,7 @@
             return;
         }
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             final Task childTask = child.mContainer;
             if (childTask == null) {
                 Slog.e(TAG_WM, "positionChildAtTop: task=" + child + " not found");
@@ -155,7 +155,7 @@
             return;
         }
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             final Task childTask = child.mContainer;
             if (childTask == null) {
                 Slog.e(TAG_WM, "positionChildAtBottom: task=" + child + " not found");
@@ -179,7 +179,7 @@
      */
     public void resize(Rect bounds, SparseArray<Rect> taskBounds,
             SparseArray<Rect> taskTempInsetBounds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 throw new IllegalArgumentException("resizeStack: stack " + this + " not found.");
             }
@@ -194,7 +194,7 @@
     }
 
     public void onPipAnimationEndResize() {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             mContainer.onPipAnimationEndResize();
         }
     }
@@ -204,7 +204,7 @@
      */
    public void getStackDockedModeBounds(Rect currentTempTaskBounds, Rect outStackBounds,
            Rect outTempTaskBounds, boolean ignoreVisibility) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer != null) {
                 mContainer.getStackDockedModeBoundsLocked(currentTempTaskBounds, outStackBounds,
                         outTempTaskBounds, ignoreVisibility);
@@ -216,7 +216,7 @@
     }
 
     public void prepareFreezingTaskBounds() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 throw new IllegalArgumentException("prepareFreezingTaskBounds: stack " + this
                         + " not found.");
@@ -226,7 +226,7 @@
     }
 
     public void getRawBounds(Rect outBounds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer.matchParentBounds()) {
                 outBounds.setEmpty();
             } else {
@@ -236,7 +236,7 @@
     }
 
     public void getBounds(Rect outBounds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer != null) {
                 mContainer.getBounds(outBounds);
                 return;
@@ -246,7 +246,7 @@
     }
 
     public void getBoundsForNewConfiguration(Rect outBounds) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             mContainer.getBoundsForNewConfiguration(outBounds);
         }
     }
@@ -261,7 +261,7 @@
             Rect nonDecorBounds, Rect stableBounds, boolean overrideWidth,
             boolean overrideHeight, float density, Configuration config,
             Configuration parentConfig, int windowingMode) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final TaskStack stack = mContainer;
             final DisplayContent displayContent = stack.getDisplayContent();
             final DisplayInfo di = displayContent.getDisplayInfo();
diff --git a/services/core/java/com/android/server/wm/SurfaceAnimator.java b/services/core/java/com/android/server/wm/SurfaceAnimator.java
index ba3d091..3ea615a 100644
--- a/services/core/java/com/android/server/wm/SurfaceAnimator.java
+++ b/services/core/java/com/android/server/wm/SurfaceAnimator.java
@@ -71,7 +71,7 @@
     private OnAnimationFinishedCallback getFinishedCallback(
             @Nullable Runnable animationFinishedCallback) {
         return anim -> {
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 final SurfaceAnimator target = mService.mAnimationTransferMap.remove(anim);
                 if (target != null) {
                     target.mInnerAnimationFinishedCallback.onAnimationFinished(anim);
diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java
index 2a529d9..3f394a2 100644
--- a/services/core/java/com/android/server/wm/Task.java
+++ b/services/core/java/com/android/server/wm/Task.java
@@ -227,7 +227,7 @@
         }
     }
 
-    /** @see com.android.server.am.ActivityTaskManagerService#positionTaskInStack(int, int, int). */
+    /** @see ActivityTaskManagerService#positionTaskInStack(int, int, int). */
     void positionAt(int position) {
         mStack.positionChildAt(position, this, false /* includingParents */);
     }
diff --git a/services/core/java/com/android/server/am/TaskChangeNotificationController.java b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
similarity index 99%
rename from services/core/java/com/android/server/am/TaskChangeNotificationController.java
rename to services/core/java/com/android/server/wm/TaskChangeNotificationController.java
index efb80be..3b3feac 100644
--- a/services/core/java/com/android/server/am/TaskChangeNotificationController.java
+++ b/services/core/java/com/android/server/wm/TaskChangeNotificationController.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.app.ActivityManager.TaskSnapshot;
 import android.app.ITaskStackListener;
diff --git a/services/core/java/com/android/server/am/TaskLaunchParamsModifier.java b/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
similarity index 98%
rename from services/core/java/com/android/server/am/TaskLaunchParamsModifier.java
rename to services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
index c15b4ac..b7804e8 100644
--- a/services/core/java/com/android/server/am/TaskLaunchParamsModifier.java
+++ b/services/core/java/com/android/server/wm/TaskLaunchParamsModifier.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
@@ -35,8 +35,8 @@
 import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.Display.INVALID_DISPLAY;
 
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
 
 import android.annotation.NonNull;
 import android.annotation.Nullable;
@@ -49,8 +49,8 @@
 import android.util.Slog;
 import android.view.Gravity;
 
-import com.android.server.am.LaunchParamsController.LaunchParams;
-import com.android.server.am.LaunchParamsController.LaunchParamsModifier;
+import com.android.server.wm.LaunchParamsController.LaunchParams;
+import com.android.server.wm.LaunchParamsController.LaunchParamsModifier;
 
 import java.util.ArrayList;
 import java.util.List;
diff --git a/services/core/java/com/android/server/am/TaskPersister.java b/services/core/java/com/android/server/wm/TaskPersister.java
similarity index 99%
rename from services/core/java/com/android/server/am/TaskPersister.java
rename to services/core/java/com/android/server/wm/TaskPersister.java
index fc5dfb4..9705d42 100644
--- a/services/core/java/com/android/server/am/TaskPersister.java
+++ b/services/core/java/com/android/server/wm/TaskPersister.java
@@ -14,9 +14,9 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
-import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
+import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS;
 
 import android.annotation.NonNull;
 import android.graphics.Bitmap;
diff --git a/services/core/java/com/android/server/wm/TaskPositioner.java b/services/core/java/com/android/server/wm/TaskPositioner.java
index d2696c0..66ebc9b 100644
--- a/services/core/java/com/android/server/wm/TaskPositioner.java
+++ b/services/core/java/com/android/server/wm/TaskPositioner.java
@@ -159,7 +159,7 @@
                         if (DEBUG_TASK_POSITIONING){
                             Slog.w(TAG, "ACTION_MOVE @ {" + newX + ", " + newY + "}");
                         }
-                        synchronized (mService.mWindowMap) {
+                        synchronized (mService.mGlobalLock) {
                             mDragEnded = notifyMoveLocked(newX, newY);
                             mTask.getDimBounds(mTmpRect);
                         }
@@ -192,7 +192,7 @@
 
                 if (mDragEnded) {
                     final boolean wasResizing = mResizing;
-                    synchronized (mService.mWindowMap) {
+                    synchronized (mService.mGlobalLock) {
                         endDragLocked();
                         mTask.getDimBounds(mTmpRect);
                     }
@@ -397,7 +397,7 @@
         // bounds yet. This will guarantee that the app starts the backdrop renderer before
         // configuration changes which could cause an activity restart.
         if (mResizing) {
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 notifyMoveLocked(startX, startY);
             }
 
diff --git a/services/core/java/com/android/server/wm/TaskPositioningController.java b/services/core/java/com/android/server/wm/TaskPositioningController.java
index 25148d1..f2d3dca 100644
--- a/services/core/java/com/android/server/wm/TaskPositioningController.java
+++ b/services/core/java/com/android/server/wm/TaskPositioningController.java
@@ -61,7 +61,7 @@
 
     boolean startMovingTask(IWindow window, float startX, float startY) {
         WindowState win = null;
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             win = mService.windowForClientLocked(null, window, false);
             // win shouldn't be null here, pass it down to startPositioningLocked
             // to get warning if it's null.
@@ -79,7 +79,7 @@
     void handleTapOutsideTask(DisplayContent displayContent, int x, int y) {
         mHandler.post(() -> {
             int taskId = -1;
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 final Task task = displayContent.findTaskForResizePoint(x, y);
                 if (task != null) {
                     if (!startPositioningLocked(task.getTopVisibleAppMainWindow(), true /*resize*/,
@@ -152,7 +152,7 @@
         mHandler.post(() -> {
             if (DEBUG_TASK_POSITIONING) Slog.d(TAG_WM, "finishPositioning");
 
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 if (mTaskPositioner != null) {
                     mTaskPositioner.unregister();
                     mTaskPositioner = null;
diff --git a/services/core/java/com/android/server/am/TaskRecord.java b/services/core/java/com/android/server/wm/TaskRecord.java
similarity index 98%
rename from services/core/java/com/android/server/am/TaskRecord.java
rename to services/core/java/com/android/server/wm/TaskRecord.java
index 5f59163..d697f28 100644
--- a/services/core/java/com/android/server/am/TaskRecord.java
+++ b/services/core/java/com/android/server/wm/TaskRecord.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityTaskManager.INVALID_STACK_ID;
 import static android.app.ActivityTaskManager.INVALID_TASK_ID;
@@ -46,22 +46,22 @@
 import static android.os.Trace.TRACE_TAG_ACTIVITY_MANAGER;
 import static android.provider.Settings.Secure.USER_SETUP_COMPLETE;
 import static android.view.Display.DEFAULT_DISPLAY;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_ADD_REMOVE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_RECENTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_ADD_REMOVE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.am.ActivityRecord.STARTING_WINDOW_SHOWN;
-import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
-import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING_TO_TOP;
-import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
-import static com.android.server.am.ActivityStackSupervisor.PAUSE_IMMEDIATELY;
-import static com.android.server.am.ActivityStackSupervisor.PRESERVE_WINDOWS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ADD_REMOVE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_LOCKTASK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RECENTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_ADD_REMOVE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_LOCKTASK;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RECENTS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityRecord.STARTING_WINDOW_SHOWN;
+import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_MOVING;
+import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_MOVING_TO_TOP;
+import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
+import static com.android.server.wm.ActivityStackSupervisor.PAUSE_IMMEDIATELY;
+import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS;
 import static com.android.server.am.TaskRecordProto.ACTIVITIES;
 import static com.android.server.am.TaskRecordProto.ACTIVITY_TYPE;
 import static com.android.server.am.TaskRecordProto.BOUNDS;
@@ -109,13 +109,7 @@
 import com.android.internal.annotations.VisibleForTesting;
 import com.android.internal.app.IVoiceInteractor;
 import com.android.internal.util.XmlUtils;
-import com.android.server.am.ActivityStack.ActivityState;
-import com.android.server.wm.AppWindowContainerController;
-import com.android.server.wm.ConfigurationContainer;
-import com.android.server.wm.StackWindowController;
-import com.android.server.wm.TaskWindowContainerController;
-import com.android.server.wm.TaskWindowContainerListener;
-import com.android.server.wm.WindowManagerService;
+import com.android.server.wm.ActivityStack.ActivityState;
 
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotCache.java b/services/core/java/com/android/server/wm/TaskSnapshotCache.java
index 7bf4edb..8175c4a 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotCache.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotCache.java
@@ -58,7 +58,7 @@
     @Nullable TaskSnapshot getSnapshot(int taskId, int userId, boolean restoreFromDisk,
             boolean reducedResolution) {
 
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             // Try the running cache.
             final CacheEntry entry = mRunningCache.get(taskId);
             if (entry != null) {
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotController.java b/services/core/java/com/android/server/wm/TaskSnapshotController.java
index 0d5469b..b84d20d 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotController.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotController.java
@@ -436,7 +436,7 @@
         // We can't take a snapshot when screen is off, so take a snapshot now!
         mHandler.post(() -> {
             try {
-                synchronized (mService.mWindowMap) {
+                synchronized (mService.mGlobalLock) {
                     mTmpTasks.clear();
                     mService.mRoot.forAllTasks(task -> {
                         if (task.isVisible()) {
diff --git a/services/core/java/com/android/server/wm/TaskSnapshotSurface.java b/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
index 67d2be8..a7b0272 100644
--- a/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
+++ b/services/core/java/com/android/server/wm/TaskSnapshotSurface.java
@@ -149,7 +149,7 @@
         final int windowFlags;
         final int windowPrivateFlags;
         final int currentOrientation;
-        synchronized (service.mWindowMap) {
+        synchronized (service.mGlobalLock) {
             final WindowState mainWindow = token.findMainWindow();
             final Task task = token.getTask();
             if (task == null) {
@@ -248,7 +248,7 @@
 
     @Override
     public void remove() {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             final long now = SystemClock.uptimeMillis();
             if (mSizeMismatch && now - mShownTime < SIZE_MISMATCH_MINIMUM_TIME_MS) {
                 mHandler.postAtTime(this::remove, mShownTime + SIZE_MISMATCH_MINIMUM_TIME_MS);
@@ -288,7 +288,7 @@
         } else {
             drawSizeMatchSnapshot(buffer);
         }
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             mShownTime = SystemClock.uptimeMillis();
             mHasDrawn = true;
         }
@@ -422,7 +422,7 @@
                 case MSG_REPORT_DRAW:
                     final boolean hasDrawn;
                     final TaskSnapshotSurface surface = (TaskSnapshotSurface) msg.obj;
-                    synchronized (surface.mService.mWindowMap) {
+                    synchronized (surface.mService.mGlobalLock) {
                         hasDrawn = surface.mHasDrawn;
                     }
                     if (hasDrawn) {
diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java
index f39ba6d..0d98b20 100644
--- a/services/core/java/com/android/server/wm/TaskStack.java
+++ b/services/core/java/com/android/server/wm/TaskStack.java
@@ -1622,7 +1622,7 @@
 
     public boolean setPinnedStackSize(Rect stackBounds, Rect tempTaskBounds) {
         // Hold the lock since this is called from the BoundsAnimator running on the UiThread
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             if (mCancelCurrentBoundsAnimation) {
                 return false;
             }
@@ -1647,7 +1647,7 @@
     @Override  // AnimatesBounds
     public boolean onAnimationStart(boolean schedulePipModeChangedCallback, boolean forceUpdate) {
         // Hold the lock since this is called from the BoundsAnimator running on the UiThread
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             if (!isAttached()) {
                 // Don't run the animation if the stack is already detached
                 return false;
@@ -1726,7 +1726,7 @@
 
     @Override
     public boolean isAttached() {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             return mDisplayContent != null;
         }
     }
@@ -1735,7 +1735,7 @@
      * Called immediately prior to resizing the tasks at the end of the pinned stack animation.
      */
     public void onPipAnimationEndResize() {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             mBoundsAnimating = false;
             for (int i = 0; i < mChildren.size(); i++) {
                 final Task t = mChildren.get(i);
@@ -1747,7 +1747,7 @@
 
     @Override
     public boolean shouldDeferStartOnMoveToFullscreen() {
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             // Workaround for the recents animation -- normally we need to wait for the new activity
             // to show before starting the PiP animation, but because we start and show the home
             // activity early for the recents animation prior to the PiP animation starting, there
diff --git a/services/core/java/com/android/server/wm/TaskTapPointerEventListener.java b/services/core/java/com/android/server/wm/TaskTapPointerEventListener.java
index 52f8510..53d2cb0 100644
--- a/services/core/java/com/android/server/wm/TaskTapPointerEventListener.java
+++ b/services/core/java/com/android/server/wm/TaskTapPointerEventListener.java
@@ -47,7 +47,7 @@
         mDisplayContent = displayContent;
         mHandler = new Handler(mService.mH.getLooper());
         mMoveDisplayToTop = () -> {
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 mDisplayContent.getParent().positionChildAt(WindowContainer.POSITION_TOP,
                         mDisplayContent, true /* includingParents */);
             }
diff --git a/services/core/java/com/android/server/wm/TaskWindowContainerController.java b/services/core/java/com/android/server/wm/TaskWindowContainerController.java
index 8b634b1..59b2055 100644
--- a/services/core/java/com/android/server/wm/TaskWindowContainerController.java
+++ b/services/core/java/com/android/server/wm/TaskWindowContainerController.java
@@ -65,7 +65,7 @@
         mTaskId = taskId;
         mHandler = new H(new WeakReference<>(this), service.mH.getLooper());
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (DEBUG_STACK) Slog.i(TAG_WM, "TaskWindowContainerController: taskId=" + taskId
                     + " stack=" + stackController + " bounds=" + bounds);
 
@@ -93,7 +93,7 @@
 
     @Override
     public void removeContainer() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 if (DEBUG_STACK) Slog.i(TAG_WM, "removeTask: could not find taskId=" + mTaskId);
                 return;
@@ -108,7 +108,7 @@
     }
 
     public void positionChildAt(AppWindowContainerController childController, int position) {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             final AppWindowToken aToken = childController.mContainer;
             if (aToken == null) {
                 Slog.w(TAG_WM,
@@ -125,7 +125,7 @@
     }
 
     public void reparent(StackWindowController stackController, int position, boolean moveParents) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (DEBUG_STACK) Slog.i(TAG_WM, "reparent: moving taskId=" + mTaskId
                     + " to stack=" + stackController + " at " + position);
             if (mContainer == null) {
@@ -144,7 +144,7 @@
     }
 
     public void setResizeable(int resizeMode) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer != null) {
                 mContainer.setResizeable(resizeMode);
             }
@@ -152,7 +152,7 @@
     }
 
     public void resize(boolean relayout, boolean forced) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 throw new IllegalArgumentException("resizeTask: taskId " + mTaskId + " not found.");
             }
@@ -165,7 +165,7 @@
     }
 
     public void getBounds(Rect bounds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer != null) {
                 mContainer.getBounds(bounds);
                 return;
@@ -180,7 +180,7 @@
      * @param resizing Whether to put the task into drag resize mode.
      */
     public void setTaskDockedResizing(boolean resizing) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM, "setTaskDockedResizing: taskId " + mTaskId + " not found.");
                 return;
@@ -190,7 +190,7 @@
     }
 
     public void cancelWindowTransition() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM, "cancelWindowTransition: taskId " + mTaskId + " not found.");
                 return;
@@ -200,7 +200,7 @@
     }
 
     public void setTaskDescription(TaskDescription taskDescription) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 Slog.w(TAG_WM, "setTaskDescription: taskId " + mTaskId + " not found.");
                 return;
@@ -210,7 +210,7 @@
     }
 
     public boolean isDragResizing() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return mContainer.isDragResizing();
         }
     }
diff --git a/services/core/java/com/android/server/am/UnsupportedCompileSdkDialog.java b/services/core/java/com/android/server/wm/UnsupportedCompileSdkDialog.java
similarity index 98%
rename from services/core/java/com/android/server/am/UnsupportedCompileSdkDialog.java
rename to services/core/java/com/android/server/wm/UnsupportedCompileSdkDialog.java
index 7348a0d..6a878b9 100644
--- a/services/core/java/com/android/server/am/UnsupportedCompileSdkDialog.java
+++ b/services/core/java/com/android/server/wm/UnsupportedCompileSdkDialog.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.app.AlertDialog;
 import android.content.Context;
diff --git a/services/core/java/com/android/server/am/UnsupportedDisplaySizeDialog.java b/services/core/java/com/android/server/wm/UnsupportedDisplaySizeDialog.java
similarity index 98%
rename from services/core/java/com/android/server/am/UnsupportedDisplaySizeDialog.java
rename to services/core/java/com/android/server/wm/UnsupportedDisplaySizeDialog.java
index 1d6438c..4a800c4 100644
--- a/services/core/java/com/android/server/am/UnsupportedDisplaySizeDialog.java
+++ b/services/core/java/com/android/server/wm/UnsupportedDisplaySizeDialog.java
@@ -14,7 +14,7 @@
  * limitations under the License.
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import com.android.internal.R;
 
diff --git a/services/core/java/com/android/server/am/VrController.java b/services/core/java/com/android/server/wm/VrController.java
similarity index 98%
rename from services/core/java/com/android/server/am/VrController.java
rename to services/core/java/com/android/server/wm/VrController.java
index 51d86d6..abe40a7 100644
--- a/services/core/java/com/android/server/am/VrController.java
+++ b/services/core/java/com/android/server/wm/VrController.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.content.ComponentName;
 import android.os.Process;
@@ -24,6 +24,9 @@
 import android.util.proto.ProtoUtils;
 
 import com.android.server.LocalServices;
+import com.android.server.am.ActivityManagerService;
+import com.android.server.am.ProcessList;
+import com.android.server.am.VrControllerProto;
 import com.android.server.vr.VrManagerInternal;
 
 /**
diff --git a/services/core/java/com/android/server/wm/WallpaperController.java b/services/core/java/com/android/server/wm/WallpaperController.java
index 942cdb9..29e1b20 100644
--- a/services/core/java/com/android/server/wm/WallpaperController.java
+++ b/services/core/java/com/android/server/wm/WallpaperController.java
@@ -340,7 +340,7 @@
                             try {
                                 if (DEBUG_WALLPAPER) Slog.v(TAG,
                                         "Waiting for offset complete...");
-                                mService.mWindowMap.wait(WALLPAPER_TIMEOUT);
+                                mService.mGlobalLock.wait(WALLPAPER_TIMEOUT);
                             } catch (InterruptedException e) {
                             }
                             if (DEBUG_WALLPAPER) Slog.v(TAG, "Offset complete!");
@@ -452,7 +452,7 @@
         if (mWaitingOnWallpaper != null &&
                 mWaitingOnWallpaper.mClient.asBinder() == window) {
             mWaitingOnWallpaper = null;
-            mService.mWindowMap.notifyAll();
+            mService.mGlobalLock.notifyAll();
         }
     }
 
@@ -460,7 +460,7 @@
         if (mWaitingOnWallpaper != null &&
                 mWaitingOnWallpaper.mClient.asBinder() == window) {
             mWaitingOnWallpaper = null;
-            mService.mWindowMap.notifyAll();
+            mService.mGlobalLock.notifyAll();
         }
     }
 
diff --git a/services/core/java/com/android/server/wm/WindowAnimator.java b/services/core/java/com/android/server/wm/WindowAnimator.java
index bc0f19a..46bb981 100644
--- a/services/core/java/com/android/server/wm/WindowAnimator.java
+++ b/services/core/java/com/android/server/wm/WindowAnimator.java
@@ -94,7 +94,7 @@
                 () -> mChoreographer = Choreographer.getSfInstance(), 0 /* timeout */);
 
         mAnimationFrameCallback = frameTimeNs -> {
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 mAnimationFrameCallbackScheduled = false;
             }
             animate(frameTimeNs);
@@ -130,7 +130,7 @@
      */
     private void animate(long frameTimeNs) {
 
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             if (!mInitialized) {
                 return;
             }
@@ -139,7 +139,7 @@
             scheduleAnimation();
         }
 
-        synchronized (mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             mCurrentTime = frameTimeNs / TimeUtils.NANOS_PER_MS;
             mBulkUpdateParams = SET_ORIENTATION_CHANGE_COMPLETE;
             mAnimating = false;
diff --git a/services/core/java/com/android/server/wm/WindowContainerController.java b/services/core/java/com/android/server/wm/WindowContainerController.java
index eb23faf..7cb89c5 100644
--- a/services/core/java/com/android/server/wm/WindowContainerController.java
+++ b/services/core/java/com/android/server/wm/WindowContainerController.java
@@ -32,7 +32,7 @@
 
     final WindowManagerService mService;
     final RootWindowContainer mRoot;
-    final WindowHashMap mWindowMap;
+    final WindowManagerGlobalLock mGlobalLock;
 
     // The window container this controller owns.
     E mContainer;
@@ -43,7 +43,7 @@
         mListener = listener;
         mService = service;
         mRoot = mService != null ? mService.mRoot : null;
-        mWindowMap = mService != null ? mService.mWindowMap : null;
+        mGlobalLock = mService != null ? mService.mGlobalLock : null;
     }
 
     void setContainer(E container) {
@@ -73,7 +73,7 @@
 
     @Override
     public void onOverrideConfigurationChanged(Configuration overrideConfiguration) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mContainer == null) {
                 return;
             }
diff --git a/services/core/java/com/android/server/wm/WindowManagerGlobalLock.java b/services/core/java/com/android/server/wm/WindowManagerGlobalLock.java
new file mode 100644
index 0000000..7ce11ee
--- /dev/null
+++ b/services/core/java/com/android/server/wm/WindowManagerGlobalLock.java
@@ -0,0 +1,9 @@
+package com.android.server.wm;
+
+/**
+ * Class that is used to generate an instance of the WM global lock. We are only doing this because
+ * we need a class for the pattern used in frameworks/base/services/core/Android.bp for CPU boost
+ * in the WM critical section.
+ */
+public class WindowManagerGlobalLock {
+}
diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java
index 96fc2e2..a641f75 100644
--- a/services/core/java/com/android/server/wm/WindowManagerService.java
+++ b/services/core/java/com/android/server/wm/WindowManagerService.java
@@ -437,18 +437,11 @@
      */
     final ArraySet<Session> mSessions = new ArraySet<>();
 
-    /**
-     * Mapping from an IWindow IBinder to the server's Window object.
-     * This is also used as the lock for all of our state.
-     * NOTE: Never call into methods that lock ActivityManagerService while holding this object.
-     */
+    /** Mapping from an IWindow IBinder to the server's Window object. */
     final WindowHashMap mWindowMap = new WindowHashMap();
 
-    /**
-     * List of window tokens that have finished starting their application,
-     * and now need to have the policy remove their windows.
-     */
-    final ArrayList<AppWindowToken> mFinishedStarting = new ArrayList<>();
+    /** Global service lock used by the package the owns this service. */
+    WindowManagerGlobalLock mGlobalLock = new WindowManagerGlobalLock();
 
     /**
      * List of app window tokens that are waiting for replacing windows. If the
@@ -780,7 +773,7 @@
     void openSurfaceTransaction() {
         try {
             Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "openSurfaceTransaction");
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 SurfaceControl.openTransaction();
             }
         } finally {
@@ -795,7 +788,7 @@
     void closeSurfaceTransaction(String where) {
         try {
             Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "closeSurfaceTransaction");
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 try {
                     traceStateLocked(where);
                 } finally {
@@ -937,7 +930,7 @@
 
                 @Override
                 public void onLowPowerModeChanged(PowerSaveState result) {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         final boolean enabled = result.batterySaverEnabled;
                         if (mAnimationsDisabled != enabled && !mAllowAnimationsInLowPowerMode) {
                             mAnimationsDisabled = enabled;
@@ -1084,7 +1077,7 @@
         final int callingUid = Binder.getCallingUid();
         final int type = attrs.type;
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (!mDisplayReady) {
                 throw new IllegalStateException("Display has not been initialialized");
             }
@@ -1455,7 +1448,7 @@
             if (localLOGV || DEBUG_ADD_REMOVE) Slog.v(TAG_WM, "addWindow: New client "
                     + client.asBinder() + ": window=" + win + " Callers=" + Debug.getCallers(5));
 
-            if (win.isVisibleOrAdding() && updateOrientationFromAppTokensLocked(displayId)) {
+            if (win.isVisibleOrAdding() && displayContent.updateOrientationFromAppTokens()) {
                 reportNewConfig = true;
             }
         }
@@ -1594,7 +1587,7 @@
             throw new SecurityException("Only system can call refreshScreenCaptureDisabled.");
         }
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             // Update secure surface for all windows belonging to this user.
             mRoot.setSecureSurfaceState(userId,
                     DevicePolicyCache.getInstance().getScreenCaptureDisabled(userId));
@@ -1602,7 +1595,7 @@
     }
 
     void removeWindow(Session session, IWindow client) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             WindowState win = windowForClientLocked(session, client, false);
             if (win == null) {
                 return;
@@ -1683,13 +1676,13 @@
     }
 
     private void updateHiddenWhileSuspendedState(ArraySet<String> packages, boolean suspended) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.updateHiddenWhileSuspendedState(packages, suspended);
         }
     }
 
     private void updateAppOpsState() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.updateAppOpsState();
         }
     }
@@ -1720,7 +1713,7 @@
     void setTransparentRegionWindow(Session session, IWindow client, Region region) {
         long origId = Binder.clearCallingIdentity();
         try {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 WindowState w = windowForClientLocked(session, client, false);
                 if (SHOW_TRANSACTIONS) WindowManagerService.logSurface(w,
                         "transparentRegionHint=" + region, false);
@@ -1738,7 +1731,7 @@
             Rect visibleInsets, Region touchableRegion) {
         long origId = Binder.clearCallingIdentity();
         try {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 WindowState w = windowForClientLocked(session, client, false);
                 if (DEBUG_LAYOUT) Slog.d(TAG, "setInsetsWindow " + w
                         + ", contentInsets=" + w.mGivenContentInsets + " -> " + contentInsets
@@ -1773,7 +1766,7 @@
 
     public void getWindowDisplayFrame(Session session, IWindow client,
             Rect outDisplayFrame) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             WindowState win = windowForClientLocked(session, client, false);
             if (win == null) {
                 outDisplayFrame.setEmpty();
@@ -1784,7 +1777,7 @@
     }
 
     public void onRectangleOnScreenRequested(IBinder token, Rect rectangle) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mAccessibilityController != null) {
                 WindowState window = mWindowMap.get(token);
                 //TODO (multidisplay): Magnification is supported only for the default display.
@@ -1796,14 +1789,14 @@
     }
 
     public IWindowId getWindowId(IBinder token) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             WindowState window = mWindowMap.get(token);
             return window != null ? window.mWindowId : null;
         }
     }
 
     public void pokeDrawLock(Session session, IBinder token) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             WindowState window = windowForClientLocked(session, token, false);
             if (window != null) {
                 window.pokeDrawLockLw(mDrawLockTimeoutMillis);
@@ -1828,7 +1821,7 @@
 
         long origId = Binder.clearCallingIdentity();
         final int displayId;
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             WindowState win = windowForClientLocked(session, client, false);
             if (win == null) {
                 return 0;
@@ -2067,7 +2060,7 @@
 
             Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER,
                     "relayoutWindow: updateOrientationFromAppTokens");
-            configChanged = updateOrientationFromAppTokensLocked(displayId);
+            configChanged = dc.updateOrientationFromAppTokens();
             Trace.traceEnd(TRACE_TAG_WINDOW_MANAGER);
 
             if (toBeDisplayed && win.mIsWallpaper) {
@@ -2222,7 +2215,7 @@
         final long origId = Binder.clearCallingIdentity();
 
         try {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 WindowState win = windowForClientLocked(session, client, false);
                 if (win == null) {
                     return false;
@@ -2237,7 +2230,7 @@
     void finishDrawingWindow(Session session, IWindow client) {
         final long origId = Binder.clearCallingIdentity();
         try {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 WindowState win = windowForClientLocked(session, client, false);
                 if (DEBUG_ADD_REMOVE) Slog.d(TAG_WM, "finishDrawingWindow: " + win + " mDrawState="
                         + (win != null ? win.mWinAnimator.drawStateToString() : "null"));
@@ -2277,7 +2270,7 @@
             throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
         }
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent dc = mRoot.getDisplayContent(displayId);
             if (dc == null) {
                 Slog.w(TAG_WM, "addWindowToken: Attempted to add token: " + binder
@@ -2309,7 +2302,7 @@
 
         final long origId = Binder.clearCallingIdentity();
         try {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent dc = mRoot.getDisplayContent(displayId);
                 if (dc == null) {
                     Slog.w(TAG_WM, "removeWindowToken: Attempted to remove token: " + binder
@@ -2347,7 +2340,7 @@
         final Configuration config;
         final long ident = Binder.clearCallingIdentity();
         try {
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 config = updateOrientationFromAppTokensLocked(currentConfig, freezeThisOneIfNeeded,
                         displayId, forceUpdate);
             }
@@ -2358,6 +2351,15 @@
         return config;
     }
 
+    /**
+     * Update orientation of the target display, returning a non-null new Configuration if it has
+     * changed from the current orientation. If a non-null configuration is returned, someone must
+     * call {@link #setNewDisplayOverrideConfiguration(Configuration, int)} to tell the window
+     * manager it can unfreeze the screen. This will typically be done by calling
+     * {@link #sendNewConfiguration(int)}.
+     *
+     * @see android.view.IWindowManager#updateOrientationFromAppTokens(Configuration, IBinder, int)
+     */
     private Configuration updateOrientationFromAppTokensLocked(Configuration currentConfig,
             IBinder freezeThisOneIfNeeded, int displayId, boolean forceUpdate) {
         if (!mDisplayReady) {
@@ -2365,7 +2367,8 @@
         }
         Configuration config = null;
 
-        if (updateOrientationFromAppTokensLocked(displayId, forceUpdate)) {
+        final DisplayContent dc = mRoot.getDisplayContent(displayId);
+        if (dc != null && dc.updateOrientationFromAppTokens(forceUpdate)) {
             // If we changed the orientation but mOrientationChangeComplete is already true,
             // we used seamless rotation, and we don't need to freeze the screen.
             if (freezeThisOneIfNeeded != null && !mRoot.mOrientationChangeComplete) {
@@ -2400,50 +2403,13 @@
         return config;
     }
 
-    /**
-     * Determine the new desired orientation of the display, returning a non-null new Configuration
-     * if it has changed from the current orientation.  IF TRUE IS RETURNED SOMEONE MUST CALL
-     * {@link #setNewDisplayOverrideConfiguration(Configuration, int)} TO TELL THE WINDOW MANAGER IT
-     * CAN UNFREEZE THE SCREEN.  This will typically be done for you if you call
-     * {@link #sendNewConfiguration(int)}.
-     *
-     * The orientation is computed from non-application windows first. If none of the
-     * non-application windows specify orientation, the orientation is computed from application
-     * tokens.
-     * @see android.view.IWindowManager#updateOrientationFromAppTokens(Configuration, IBinder, int)
-     */
-    boolean updateOrientationFromAppTokensLocked(int displayId) {
-        return updateOrientationFromAppTokensLocked(displayId, false /* forceUpdate */);
-    }
-
-    boolean updateOrientationFromAppTokensLocked(int displayId, boolean forceUpdate) {
-        long ident = Binder.clearCallingIdentity();
-        try {
-            final DisplayContent dc = mRoot.getDisplayContent(displayId);
-            if (dc == null) {
-                return false;
-            }
-            final int req = dc.getOrientation();
-            if (req != dc.getLastOrientation() || forceUpdate) {
-                dc.setLastOrientation(req);
-                //send a message to Policy indicating orientation change to take
-                //action like disabling/enabling sensors etc.,
-                dc.getDisplayRotation().setCurrentOrientation(req);
-                return dc.updateRotationUnchecked(forceUpdate);
-            }
-            return false;
-        } finally {
-            Binder.restoreCallingIdentity(ident);
-        }
-    }
-
     @Override
     public int[] setNewDisplayOverrideConfiguration(Configuration overrideConfig, int displayId) {
         if (!checkCallingPermission(MANAGE_APP_TOKENS, "setNewDisplayOverrideConfiguration()")) {
             throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
         }
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mWaitingForConfig) {
                 mWaitingForConfig = false;
                 mLastFinishedFreezeSource = "new-config";
@@ -2468,7 +2434,7 @@
     public void overridePendingAppTransitionMultiThumbFuture(
             IAppTransitionAnimationSpecsFuture specsFuture, IRemoteCallback callback,
             boolean scaleUp) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             // TODO(multi-display): sysui using this api only support default display.
             mRoot.getDisplayContent(DEFAULT_DISPLAY)
                     .mAppTransition.overridePendingAppTransitionMultiThumbFuture(specsFuture,
@@ -2483,7 +2449,7 @@
             throw new SecurityException(
                     "Requires CONTROL_REMOTE_APP_TRANSITION_ANIMATIONS permission");
         }
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             // TODO(multi-display): sysui using this api only support default display.
             mRoot.getDisplayContent(DEFAULT_DISPLAY)
                     .mAppTransition.overridePendingAppTransitionRemote(remoteAnimationAdapter);
@@ -2509,7 +2475,7 @@
             IRecentsAnimationRunner recentsAnimationRunner,
             RecentsAnimationController.RecentsAnimationCallbacks callbacks, int displayId,
             SparseBooleanArray recentTaskIds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRecentsAnimationController = new RecentsAnimationController(this,
                     recentsAnimationRunner, callbacks, displayId);
             mRoot.getDisplayContent(displayId).mAppTransition.updateBooster();
@@ -2531,7 +2497,7 @@
      *         {@link RecentsAnimation#startRecentsActivity}.
      */
     public boolean canStartRecentsAnimation() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             // TODO(multi-display): currently only default display support recent activity
             if (getDefaultDisplayContentLocked().mAppTransition.isTransitionSet()) {
                 return false;
@@ -2555,7 +2521,7 @@
     }
 
     public void cleanupRecentsAnimation(@RecentsAnimationController.ReorderMode int reorderMode) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mRecentsAnimationController != null) {
                 final RecentsAnimationController controller = mRecentsAnimationController;
                 mRecentsAnimationController = null;
@@ -2567,7 +2533,7 @@
     }
 
     public void setAppFullscreen(IBinder token, boolean toOpaque) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final AppWindowToken atoken = mRoot.getAppWindowToken(token);
             if (atoken != null) {
                 atoken.setFillsParent(toOpaque);
@@ -2578,7 +2544,7 @@
     }
 
     public void setWindowOpaque(IBinder token, boolean isOpaque) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             setWindowOpaqueLocked(token, isOpaque);
         }
     }
@@ -2594,7 +2560,7 @@
     }
 
     public void setDockedStackCreateState(int mode, Rect bounds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             setDockedStackCreateStateLocked(mode, bounds);
         }
     }
@@ -2605,7 +2571,7 @@
     }
 
     public void checkSplitScreenMinimizedChanged(boolean animate) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = getDefaultDisplayContentLocked();
             displayContent.getDockedDividerController().checkMinimizeChanged(animate);
         }
@@ -2619,7 +2585,7 @@
 
     @Override
     public void getStackBounds(int windowingMode, int activityType, Rect bounds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final TaskStack stack = mRoot.getStack(windowingMode, activityType);
             if (stack != null) {
                 stack.getBounds(bounds);
@@ -2666,7 +2632,7 @@
      * layouting will be resumed once the last caller has called {@link #continueSurfaceLayout}
      */
     public void deferSurfaceLayout() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mWindowPlacerLocked.deferLayout();
         }
     }
@@ -2675,7 +2641,7 @@
      * Resumes layout passes after deferring them. See {@link #deferSurfaceLayout()}
      */
     public void continueSurfaceLayout() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mWindowPlacerLocked.continueLayout();
         }
     }
@@ -2685,7 +2651,7 @@
      *         {@link LayoutParams#FLAG_SHOW_WHEN_LOCKED} set
      */
     public boolean containsShowWhenLockedWindow(IBinder token) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final AppWindowToken wtoken = mRoot.getAppWindowToken(token);
             return wtoken != null && wtoken.containsShowWhenLockedWindow();
         }
@@ -2696,7 +2662,7 @@
      *         {@link LayoutParams#FLAG_DISMISS_KEYGUARD} set
      */
     public boolean containsDismissKeyguardWindow(IBinder token) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final AppWindowToken wtoken = mRoot.getAppWindowToken(token);
             return wtoken != null && wtoken.containsDismissKeyguardWindow();
         }
@@ -2709,26 +2675,26 @@
      */
     void notifyKeyguardFlagsChanged(@Nullable Runnable callback, int displayId) {
         final Runnable wrappedCallback = callback != null
-                ? () -> { synchronized (mWindowMap) { callback.run(); } }
+                ? () -> { synchronized (mGlobalLock) { callback.run(); } }
                 : null;
         mH.obtainMessage(H.NOTIFY_KEYGUARD_FLAGS_CHANGED, displayId, 0,
                 wrappedCallback).sendToTarget();
     }
 
     public boolean isKeyguardTrusted() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return mPolicy.isKeyguardTrustedLw();
         }
     }
 
     public void setKeyguardGoingAway(boolean keyguardGoingAway) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mKeyguardGoingAway = keyguardGoingAway;
         }
     }
 
     public void setKeyguardOrAodShowingOnDefaultDisplay(boolean showing) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mKeyguardOrAodShowingOnDefaultDisplay = showing;
         }
     }
@@ -2744,7 +2710,7 @@
             throw new SecurityException("Requires FREEZE_SCREEN permission");
         }
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (!mClientFreezingScreen) {
                 mClientFreezingScreen = true;
                 final long origId = Binder.clearCallingIdentity();
@@ -2766,7 +2732,7 @@
             throw new SecurityException("Requires FREEZE_SCREEN permission");
         }
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mClientFreezingScreen) {
                 mClientFreezingScreen = false;
                 mLastFinishedFreezeSource = "client";
@@ -2869,7 +2835,7 @@
     }
 
     public boolean isShowingDream() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return mPolicy.isShowingDreamLw();
         }
     }
@@ -2879,13 +2845,13 @@
         if (!checkCallingPermission(permission.CONTROL_KEYGUARD, "dismissKeyguard")) {
             throw new SecurityException("Requires CONTROL_KEYGUARD permission");
         }
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             mPolicy.dismissKeyguardLw(callback, message);
         }
     }
 
     public void onKeyguardOccludedChanged(boolean occluded) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mPolicy.onKeyguardOccludedChangedLw(occluded);
         }
     }
@@ -2897,7 +2863,7 @@
             throw new SecurityException("Requires INTERACT_ACROSS_USERS_FULL permission");
         }
         mPolicy.setSwitchingUser(switching);
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mSwitchingUser = switching;
         }
     }
@@ -2908,7 +2874,7 @@
 
     @Override
     public void closeSystemDialogs(String reason) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.closeSystemDialogs(reason);
         }
     }
@@ -2992,7 +2958,7 @@
 
     @Override
     public float getCurrentAnimatorScale() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             return mAnimationsDisabled ? 0 : mAnimatorDurationScaleSetting;
         }
     }
@@ -3003,7 +2969,7 @@
 
     @Override
     public void registerPointerEventListener(PointerEventListener listener, int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent != null) {
                 displayContent.registerPointerEventListener(listener);
@@ -3013,7 +2979,7 @@
 
     @Override
     public void unregisterPointerEventListener(PointerEventListener listener, int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent != null) {
                 displayContent.unregisterPointerEventListener(listener);
@@ -3092,13 +3058,13 @@
     }
 
     public void setCurrentProfileIds(final int[] currentProfileIds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mCurrentProfileIds = currentProfileIds;
         }
     }
 
     public void setCurrentUser(final int newUserId, final int[] currentProfileIds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mCurrentUserId = newUserId;
             mCurrentProfileIds = currentProfileIds;
             mPolicy.setCurrentUserLw(newUserId);
@@ -3142,7 +3108,7 @@
     }
 
     public void enableScreenAfterBoot() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (DEBUG_BOOT) {
                 RuntimeException here = new RuntimeException("here");
                 here.fillInStackTrace();
@@ -3168,7 +3134,7 @@
 
     @Override
     public void enableScreenIfNeeded() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             enableScreenIfNeededLocked();
         }
     }
@@ -3192,7 +3158,7 @@
     }
 
     public void performBootTimeout() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mDisplayEnabled) {
                 return;
             }
@@ -3210,7 +3176,7 @@
     }
 
     private void performEnableScreen() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (DEBUG_BOOT) Slog.i(TAG_WM, "performEnableScreen: mDisplayEnabled=" + mDisplayEnabled
                     + " mForceDisplayEnabled=" + mForceDisplayEnabled
                     + " mShowingBootMessages=" + mShowingBootMessages
@@ -3297,7 +3263,7 @@
 
     public void showBootMessage(final CharSequence msg, final boolean always) {
         boolean first = false;
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if (DEBUG_BOOT) {
                 RuntimeException here = new RuntimeException("here");
                 here.fillInStackTrace();
@@ -3343,7 +3309,7 @@
 
     @Override
     public void setInTouchMode(boolean mode) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             mInTouchMode = mode;
         }
     }
@@ -3353,7 +3319,7 @@
                 && mContext.getResources().getBoolean(
                 com.android.internal.R.bool.config_windowShowCircularMask)) {
             final int currentUserId;
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 currentUserId = mCurrentUserId;
             }
             // Device configuration calls for a circular display mask, but we only enable the mask
@@ -3378,7 +3344,7 @@
     }
 
     public void showCircularMask(boolean visible) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
 
             if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
                     ">>> OPEN TRANSACTION showCircularMask(visible=" + visible + ")");
@@ -3412,7 +3378,7 @@
     }
 
     public void showEmulatorDisplayOverlay() {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
 
             if (SHOW_LIGHT_TRANSACTIONS) Slog.i(TAG_WM,
                     ">>> OPEN TRANSACTION showEmulatorDisplayOverlay");
@@ -3453,7 +3419,7 @@
 
     private void showStrictModeViolation(int arg, int pid) {
         final boolean on = arg != 0;
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             // Ignoring requests to enable the red border from clients which aren't on screen.
             // (e.g. Broadcast Receivers in the background..)
             if (on && !mRoot.canShowStrictModeViolation(pid)) {
@@ -3492,7 +3458,7 @@
         }
         try {
             Trace.traceBegin(TRACE_TAG_WINDOW_MANAGER, "screenshotWallpaper");
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 return mRoot.mWallpaperController.screenshotWallpaperLocked();
             }
         } finally {
@@ -3512,7 +3478,7 @@
         }
 
         final Bitmap bm;
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(DEFAULT_DISPLAY);
             if (displayContent == null) {
                 if (DEBUG_SCREENSHOT) {
@@ -3549,7 +3515,7 @@
      *                       model.
      */
     public void removeObsoleteTaskFiles(ArraySet<Integer> persistentTaskIds, int[] runningUserIds) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mTaskSnapshotController.removeObsoleteTaskFiles(persistentTaskIds, runningUserIds);
         }
     }
@@ -3579,7 +3545,7 @@
 
         long origId = Binder.clearCallingIdentity();
         try {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent display = mRoot.getDisplayContent(displayId);
                 if (display == null) {
                     Slog.w(TAG, "Trying to freeze rotation for a missing display.");
@@ -3615,7 +3581,7 @@
 
         long origId = Binder.clearCallingIdentity();
         try {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent display = mRoot.getDisplayContent(displayId);
                 if (display == null) {
                     Slog.w(TAG, "Trying to thaw rotation for a missing display.");
@@ -3637,7 +3603,7 @@
 
     @Override
     public boolean isDisplayRotationFrozen(int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent display = mRoot.getDisplayContent(displayId);
             if (display == null) {
                 Slog.w(TAG, "Trying to thaw rotation for a missing display.");
@@ -3669,7 +3635,7 @@
         long origId = Binder.clearCallingIdentity();
 
         try {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 boolean layoutNeeded = false;
                 final int displayCount = mRoot.mChildren.size();
                 for (int i = 0; i < displayCount; ++i) {
@@ -3683,8 +3649,7 @@
                         layoutNeeded = true;
                     }
                     if (rotationChanged || alwaysSendConfiguration) {
-                        mH.obtainMessage(H.SEND_NEW_CONFIGURATION, displayContent.getDisplayId())
-                                .sendToTarget();
+                        displayContent.sendNewConfiguration();
                     }
                 }
 
@@ -3703,14 +3668,14 @@
 
     @Override
     public WindowManagerPolicy.DisplayContentInfo getDefaultDisplayContentInfo() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return getDefaultDisplayContentLocked();
         }
     }
 
     @Override
     public int getDefaultDisplayRotation() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return getDefaultDisplayContentLocked().getRotation();
         }
     }
@@ -3718,7 +3683,7 @@
     @Override
     public int watchRotation(IRotationWatcher watcher, int displayId) {
         final DisplayContent displayContent;
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             displayContent = mRoot.getDisplayContent(displayId);
         }
         if (displayContent == null) {
@@ -3730,7 +3695,7 @@
         IBinder.DeathRecipient dr = new IBinder.DeathRecipient() {
             @Override
             public void binderDied() {
-                synchronized (mWindowMap) {
+                synchronized (mGlobalLock) {
                     for (int i=0; i<mRotationWatchers.size(); i++) {
                         if (watcherBinder == mRotationWatchers.get(i).mWatcher.asBinder()) {
                             RotationWatcher removed = mRotationWatchers.remove(i);
@@ -3745,7 +3710,7 @@
             }
         };
 
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             try {
                 watcher.asBinder().linkToDeath(dr, 0);
                 mRotationWatchers.add(new RotationWatcher(watcher, dr, displayId));
@@ -3760,7 +3725,7 @@
     @Override
     public void removeRotationWatcher(IRotationWatcher watcher) {
         final IBinder watcherBinder = watcher.asBinder();
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             for (int i=0; i<mRotationWatchers.size(); i++) {
                 RotationWatcher rotationWatcher = mRotationWatchers.get(i);
                 if (watcherBinder == rotationWatcher.mWatcher.asBinder()) {
@@ -3778,7 +3743,7 @@
     @Override
     public boolean registerWallpaperVisibilityListener(IWallpaperVisibilityListener listener,
             int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent == null) {
                 throw new IllegalArgumentException("Trying to register visibility event "
@@ -3792,7 +3757,7 @@
     @Override
     public void unregisterWallpaperVisibilityListener(IWallpaperVisibilityListener listener,
             int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mWallpaperVisibilityListeners
                     .unregisterWallpaperVisibilityListener(listener, displayId);
         }
@@ -3800,7 +3765,7 @@
 
     @Override
     public int getPreferredOptionsPanelGravity(int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent == null) {
                 return Gravity.CENTER | Gravity.BOTTOM;
@@ -3918,7 +3883,7 @@
         boolean result = true;
 
         final ArrayList<WindowState> windows = new ArrayList();
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.forAllWindows(w -> {
                 windows.add(w);
             }, false /* traverseTopToBottom */);
@@ -4100,20 +4065,20 @@
     }
 
     public void addWindowChangeListener(WindowChangeListener listener) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             mWindowChangeListeners.add(listener);
         }
     }
 
     public void removeWindowChangeListener(WindowChangeListener listener) {
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             mWindowChangeListeners.remove(listener);
         }
     }
 
     private void notifyWindowsChanged() {
         WindowChangeListener[] windowChangeListeners;
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if(mWindowChangeListeners.isEmpty()) {
                 return;
             }
@@ -4128,7 +4093,7 @@
 
     private void notifyFocusChanged() {
         WindowChangeListener[] windowChangeListeners;
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             if(mWindowChangeListeners.isEmpty()) {
                 return;
             }
@@ -4147,7 +4112,7 @@
             return getFocusedWindow();
         }
 
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return mRoot.getWindow((w) -> System.identityHashCode(w) == hashCode);
         }
     }
@@ -4166,7 +4131,7 @@
                 // E.g. changing device rotation by 180 degrees. Go ahead and perform surface
                 // placement to unfreeze the display since we froze it when the rotation was updated
                 // in DisplayContent#updateRotationUnchecked.
-                synchronized (mWindowMap) {
+                synchronized (mGlobalLock) {
                     if (mWaitingForConfig) {
                         mWaitingForConfig = false;
                         mLastFinishedFreezeSource = "config-unchanged";
@@ -4183,7 +4148,7 @@
     }
 
     public Configuration computeNewConfiguration(int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return computeNewConfigurationLocked(displayId);
         }
     }
@@ -4201,7 +4166,7 @@
     void notifyHardKeyboardStatusChange() {
         final boolean available;
         final WindowManagerInternal.OnHardKeyboardStatusChangeListener listener;
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             listener = mHardKeyboardStatusChangeListener;
             available = mHardKeyboardAvailable;
         }
@@ -4223,7 +4188,7 @@
             throw new SecurityException("Requires MANAGE_APP_TOKENS permission");
         }
 
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mEventDispatchingEnabled = enabled;
             if (mDisplayEnabled) {
                 mInputManagerCallback.setEventDispatchingLw(enabled);
@@ -4232,7 +4197,7 @@
     }
 
     private WindowState getFocusedWindow() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return getFocusedWindowLocked();
         }
     }
@@ -4301,7 +4266,7 @@
     }
 
     public void displayReady() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mMaxUiWidth > 0) {
                 mRoot.forAllDisplays(displayContent -> displayContent.setMaxUiWidth(mMaxUiWidth));
             }
@@ -4425,7 +4390,7 @@
 
                     AccessibilityController accessibilityController = null;
 
-                    synchronized(mWindowMap) {
+                    synchronized (mGlobalLock) {
                         // TODO(multidisplay): Accessibility supported only of default desiplay.
                         if (mAccessibilityController != null && displayContent.isDefaultDisplay) {
                             accessibilityController = mAccessibilityController;
@@ -4469,7 +4434,7 @@
                     final DisplayContent displayContent = (DisplayContent) msg.obj;
                     ArrayList<WindowState> losers;
 
-                    synchronized(mWindowMap) {
+                    synchronized (mGlobalLock) {
                         losers = displayContent.mLosingFocus;
                         displayContent.mLosingFocus = new ArrayList<>();
                     }
@@ -4484,7 +4449,7 @@
 
                 case WINDOW_FREEZE_TIMEOUT: {
                     final DisplayContent displayContent = (DisplayContent) msg.obj;
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         displayContent.onWindowFreezeTimeout();
                     }
                     break;
@@ -4532,7 +4497,7 @@
                 }
 
                 case FORCE_GC: {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         // Since we're holding both mWindowMap and mAnimator we don't need to
                         // hold mAnimator.mLayoutToAnim.
                         if (mAnimator.isAnimating() || mAnimator.isAnimationScheduled()) {
@@ -4557,7 +4522,7 @@
                 }
 
                 case APP_FREEZE_TIMEOUT: {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         Slog.w(TAG_WM, "App freeze timeout expired.");
                         mWindowsFreezingScreen = WINDOWS_FREEZING_SCREENS_TIMEOUT;
                         for (int i = mAppFreezeListeners.size() - 1; i >=0 ; --i) {
@@ -4568,7 +4533,7 @@
                 }
 
                 case CLIENT_FREEZE_TIMEOUT: {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         if (mClientFreezingScreen) {
                             mClientFreezingScreen = false;
                             mLastFinishedFreezeSource = "client-timeout";
@@ -4579,15 +4544,17 @@
                 }
 
                 case SEND_NEW_CONFIGURATION: {
-                    removeMessages(SEND_NEW_CONFIGURATION, msg.obj);
-                    final int displayId = (Integer) msg.obj;
-                    if (mRoot.getDisplayContent(displayId) != null) {
-                        sendNewConfiguration(displayId);
+                    final DisplayContent displayContent = (DisplayContent) msg.obj;
+                    removeMessages(SEND_NEW_CONFIGURATION, displayContent);
+                    if (displayContent.isReady()) {
+                        sendNewConfiguration(displayContent.getDisplayId());
                     } else {
                         // Message could come after display has already been removed.
                         if (DEBUG_CONFIGURATION) {
-                            Slog.w(TAG, "Trying to send configuration to non-existing displayId="
-                                    + displayId);
+                            final String reason = displayContent.getParent() == null
+                                    ? "detached" : "unready";
+                            Slog.w(TAG, "Trying to send configuration to " + reason + " display="
+                                    + displayContent);
                         }
                     }
                     break;
@@ -4595,7 +4562,7 @@
 
                 case REPORT_WINDOWS_CHANGE: {
                     if (mWindowsChanged) {
-                        synchronized (mWindowMap) {
+                        synchronized (mGlobalLock) {
                             mWindowsChanged = false;
                         }
                         notifyWindowsChanged();
@@ -4615,7 +4582,7 @@
 
                 case WAITING_FOR_DRAWN_TIMEOUT: {
                     Runnable callback = null;
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         Slog.w(TAG_WM, "Timeout waiting for drawn: undrawn=" + mWaitingForDrawn);
                         mWaitingForDrawn.clear();
                         callback = mWaitingForDrawnCallback;
@@ -4650,7 +4617,7 @@
                     break;
                 case ALL_WINDOWS_DRAWN: {
                     Runnable callback;
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         callback = mWaitingForDrawnCallback;
                         mWaitingForDrawnCallback = null;
                     }
@@ -4671,7 +4638,7 @@
                     } else {
                         ArrayList<IWindowSessionCallback> callbacks
                                 = new ArrayList<IWindowSessionCallback>();
-                        synchronized (mWindowMap) {
+                        synchronized (mGlobalLock) {
                             for (int i=0; i<mSessions.size(); i++) {
                                 callbacks.add(mSessions.valueAt(i).mCallback);
                             }
@@ -4688,7 +4655,7 @@
                 break;
                 case CHECK_IF_BOOT_ANIMATION_FINISHED: {
                     final boolean bootAnimationComplete;
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         if (DEBUG_BOOT) Slog.i(TAG_WM, "CHECK_IF_BOOT_ANIMATION_FINISHED:");
                         bootAnimationComplete = checkBootAnimationCompleteLocked();
                     }
@@ -4698,14 +4665,14 @@
                 }
                 break;
                 case RESET_ANR_MESSAGE: {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         mLastANRState = null;
                     }
                     mAtmInternal.clearSavedANRState();
                 }
                 break;
                 case WALLPAPER_DRAW_PENDING_TIMEOUT: {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         if (mRoot.mWallpaperController.processWallpaperDrawPendingTimeout()) {
                             mWindowPlacerLocked.performSurfacePlacement();
                         }
@@ -4713,7 +4680,7 @@
                 }
                 break;
                 case UPDATE_DOCKED_STACK_DIVIDER: {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         final DisplayContent displayContent = getDefaultDisplayContentLocked();
                         displayContent.getDockedDividerController().reevaluateVisibility(false);
                         displayContent.adjustForImeIfNeeded();
@@ -4721,7 +4688,7 @@
                 }
                 break;
                 case WINDOW_REPLACEMENT_TIMEOUT: {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         for (int i = mWindowReplacementTimeouts.size() - 1; i >= 0; i--) {
                             final AppWindowToken token = mWindowReplacementTimeouts.get(i);
                             token.onWindowReplacementTimeout();
@@ -4745,7 +4712,7 @@
                 break;
                 case WINDOW_HIDE_TIMEOUT: {
                     final WindowState window = (WindowState) msg.obj;
-                    synchronized(mWindowMap) {
+                    synchronized (mGlobalLock) {
                         // TODO: This is all about fixing b/21693547
                         // where partially initialized Toasts get stuck
                         // around and keep the screen on. We'd like
@@ -4769,14 +4736,14 @@
                 }
                 break;
                 case RESTORE_POINTER_ICON: {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         restorePointerIconLocked((DisplayContent)msg.obj, msg.arg1, msg.arg2);
                     }
                 }
                 break;
                 case SEAMLESS_ROTATION_TIMEOUT: {
                     final DisplayContent displayContent = (DisplayContent) msg.obj;
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         displayContent.onSeamlessRotationTimeout();
                     }
                 }
@@ -4798,7 +4765,7 @@
                 }
                 break;
                 case ANIMATION_FAILSAFE: {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         if (mRecentsAnimationController != null) {
                             mRecentsAnimationController.scheduleFailsafe();
                         }
@@ -4806,7 +4773,7 @@
                 }
                 break;
                 case RECOMPUTE_FOCUS: {
-                    synchronized (mWindowMap) {
+                    synchronized (mGlobalLock) {
                         updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL,
                                 true /* updateInputWindows */);
                     }
@@ -4844,7 +4811,7 @@
 
     @Override
     public void getInitialDisplaySize(int displayId, Point size) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent != null && displayContent.hasAccess(Binder.getCallingUid())) {
                 size.x = displayContent.mInitialDisplayWidth;
@@ -4855,7 +4822,7 @@
 
     @Override
     public void getBaseDisplaySize(int displayId, Point size) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent != null && displayContent.hasAccess(Binder.getCallingUid())) {
                 size.x = displayContent.mBaseDisplayWidth;
@@ -4875,7 +4842,7 @@
 
         final long ident = Binder.clearCallingIdentity();
         try {
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
                 if (displayContent != null) {
                     displayContent.setForcedSize(width, height);
@@ -4897,7 +4864,7 @@
 
         final long ident = Binder.clearCallingIdentity();
         try {
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
                 if (displayContent != null) {
                     displayContent.setForcedScalingMode(mode);
@@ -4911,7 +4878,6 @@
     /** The global settings only apply to default display. */
     private void applyForcedPropertiesForDefaultDisplay() {
         final DisplayContent displayContent = getDefaultDisplayContentLocked();
-        boolean changed = false;
         // Display size.
         String sizeStr = Settings.Global.getString(mContext.getContentResolver(),
                 Settings.Global.DISPLAY_SIZE_FORCED);
@@ -4930,7 +4896,6 @@
                         Slog.i(TAG_WM, "FORCED DISPLAY SIZE: " + width + "x" + height);
                         displayContent.updateBaseDisplayMetrics(width, height,
                                 displayContent.mBaseDisplayDensity);
-                        changed = true;
                     }
                 } catch (NumberFormatException ex) {
                 }
@@ -4941,7 +4906,6 @@
         final int density = getForcedDisplayDensityForUserLocked(mCurrentUserId);
         if (density != 0) {
             displayContent.mBaseDisplayDensity = density;
-            changed = true;
         }
 
         // Display scaling mode.
@@ -4950,11 +4914,6 @@
         if (mode != 0) {
             Slog.i(TAG_WM, "FORCED DISPLAY SCALING DISABLED");
             displayContent.mDisplayScalingDisabled = true;
-            changed = true;
-        }
-
-        if (changed) {
-            reconfigureDisplayLocked(displayContent);
         }
     }
 
@@ -4969,7 +4928,7 @@
 
         final long ident = Binder.clearCallingIdentity();
         try {
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
                 if (displayContent != null) {
                     displayContent.setForcedSize(displayContent.mInitialDisplayWidth,
@@ -4983,7 +4942,7 @@
 
     @Override
     public int getInitialDisplayDensity(int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent != null && displayContent.hasAccess(Binder.getCallingUid())) {
                 return displayContent.mInitialDisplayDensity;
@@ -4994,7 +4953,7 @@
 
     @Override
     public int getBaseDisplayDensity(int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent != null && displayContent.hasAccess(Binder.getCallingUid())) {
                 return displayContent.mBaseDisplayDensity;
@@ -5017,7 +4976,7 @@
                 null);
         final long ident = Binder.clearCallingIdentity();
         try {
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
                 if (displayContent != null) {
                     displayContent.setForcedDensity(density, targetUserId);
@@ -5042,7 +5001,7 @@
                 null);
         final long ident = Binder.clearCallingIdentity();
         try {
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
                 if (displayContent != null) {
                     displayContent.setForcedDensity(displayContent.mInitialDisplayDensity,
@@ -5081,8 +5040,7 @@
         displayContent.configureDisplayPolicy();
         displayContent.setLayoutNeeded();
 
-        final int displayId = displayContent.getDisplayId();
-        boolean configChanged = updateOrientationFromAppTokensLocked(displayId);
+        boolean configChanged = displayContent.updateOrientationFromAppTokens();
         final Configuration currentDisplayConfig = displayContent.getConfiguration();
         mTempConfiguration.setTo(currentDisplayConfig);
         displayContent.computeScreenConfiguration(mTempConfiguration);
@@ -5092,7 +5050,7 @@
             mWaitingForConfig = true;
             startFreezingDisplayLocked(0 /* exitAnim */,
                     0 /* enterAnim */, displayContent);
-            mH.obtainMessage(H.SEND_NEW_CONFIGURATION, displayId).sendToTarget();
+            displayContent.sendNewConfiguration();
         }
 
         mWindowPlacerLocked.performSurfacePlacement();
@@ -5108,7 +5066,7 @@
         }
         final long ident = Binder.clearCallingIdentity();
         try {
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 DisplayContent displayContent = mRoot.getDisplayContent(displayId);
                 if (displayContent != null) {
                     setOverscanLocked(displayContent, left, top, right, bottom);
@@ -5261,7 +5219,7 @@
     }
 
     void requestTraversal() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mWindowPlacerLocked.requestTraversal();
         }
     }
@@ -5396,7 +5354,6 @@
         if (CUSTOM_SCREEN_ROTATION && screenRotationAnimation != null
                 && screenRotationAnimation.hasScreenshot()) {
             if (DEBUG_ORIENTATION) Slog.i(TAG_WM, "**** Dismissing screen rotation animation");
-            // TODO(multidisplay): rotation on main screen only.
             DisplayInfo displayInfo = displayContent.getDisplayInfo();
             // Get rotation animation again, with new top window
             if (!mPolicy.validateRotationAnimationLw(mExitAnimId, mEnterAnimId, false)) {
@@ -5426,7 +5383,7 @@
         // to avoid inconsistent states.  However, something interesting
         // could have actually changed during that time so re-evaluate it
         // now to catch that.
-        configChanged = updateOrientationFromAppTokensLocked(displayId);
+        configChanged = displayContent != null && displayContent.updateOrientationFromAppTokens();
 
         // A little kludge: a lot could have happened while the
         // display was frozen, so now that we are coming back we
@@ -5444,7 +5401,7 @@
         }
 
         if (configChanged) {
-            mH.obtainMessage(H.SEND_NEW_CONFIGURATION, displayId).sendToTarget();
+            displayContent.sendNewConfiguration();
         }
         mLatencyTracker.onActionEnd(ACTION_ROTATE_SCREEN);
     }
@@ -5510,7 +5467,7 @@
     public void setRecentsVisibility(boolean visible) {
         mAtmInternal.enforceCallerIsRecentsOrHasPermission(android.Manifest.permission.STATUS_BAR,
                 "setRecentsVisibility()");
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mPolicy.setRecentsVisibilityLw(visible);
         }
     }
@@ -5523,7 +5480,7 @@
                     + android.Manifest.permission.STATUS_BAR);
         }
 
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mPolicy.setPipVisibilityLw(visible);
         }
     }
@@ -5532,7 +5489,7 @@
     public void setShelfHeight(boolean visible, int shelfHeight) {
         mAtmInternal.enforceCallerIsRecentsOrHasPermission(android.Manifest.permission.STATUS_BAR,
                 "setShelfHeight()");
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             getDefaultDisplayContentLocked().getPinnedStackController().setAdjustedForShelf(visible,
                     shelfHeight);
         }
@@ -5546,7 +5503,7 @@
                     + android.Manifest.permission.STATUS_BAR);
         }
 
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mLastStatusBarVisibility = visibility;
             visibility = mPolicy.adjustSystemUiVisibilityLw(visibility);
             updateStatusBarVisibilityLocked(visibility);
@@ -5560,7 +5517,7 @@
                     + android.Manifest.permission.STATUS_BAR);
         }
 
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mPolicy.setNavBarVirtualKeyHapticFeedbackEnabledLw(enabled);
         }
     }
@@ -5585,7 +5542,7 @@
 
     @Override
     public void reevaluateStatusBarVisibility() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             int visibility = mPolicy.adjustSystemUiVisibilityLw(mLastStatusBarVisibility);
             if (updateStatusBarVisibilityLocked(visibility)) {
                 mWindowPlacerLocked.requestTraversal();
@@ -5601,7 +5558,7 @@
     @Override
     @WindowManagerPolicy.NavigationBarPosition
     public int getNavBarPosition() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             // Perform layout if it was scheduled before to make sure that we get correct nav bar
             // position when doing rotations.
             final DisplayContent defaultDisplayContent = getDefaultDisplayContentLocked();
@@ -5614,7 +5571,7 @@
     @Override
     public WindowManagerPolicy.InputConsumer createInputConsumer(Looper looper, String name,
             InputEventReceiver.Factory inputEventReceiverFactory, int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent != null) {
                 return displayContent.getInputMonitor().createInputConsumer(looper, name,
@@ -5628,7 +5585,7 @@
     @Override
     public void createInputConsumer(IBinder token, String name, int displayId,
             InputChannel inputChannel) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             DisplayContent display = mRoot.getDisplayContent(displayId);
             if (display != null) {
                 display.getInputMonitor().createInputConsumer(token, name, inputChannel,
@@ -5639,7 +5596,7 @@
 
     @Override
     public boolean destroyInputConsumer(String name, int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             DisplayContent display = mRoot.getDisplayContent(displayId);
             if (display != null) {
                 return display.getInputMonitor().destroyInputConsumer(name);
@@ -5653,7 +5610,7 @@
         if (mContext.checkCallingOrSelfPermission(RESTRICTED_VR_ACCESS) != PERMISSION_GRANTED) {
             throw new SecurityException("getCurrentImeTouchRegion is restricted to VR services");
         }
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final Region r = new Region();
             // TODO(b/111080190): this method is only return the recent focused IME touch region,
             // For Multi-Session IME, will need to add API for given display Id to
@@ -5694,7 +5651,7 @@
                 "clearWindowContentFrameStats()")) {
             throw new SecurityException("Requires FRAME_STATS permission");
         }
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             WindowState windowState = mWindowMap.get(token);
             if (windowState == null) {
                 return false;
@@ -5713,7 +5670,7 @@
                 "getWindowContentFrameStats()")) {
             throw new SecurityException("Requires FRAME_STATS permission");
         }
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             WindowState windowState = mWindowMap.get(token);
             if (windowState == null) {
                 return null;
@@ -5734,7 +5691,7 @@
     }
 
     public void notifyAppRelaunching(IBinder token) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final AppWindowToken appWindow = mRoot.getAppWindowToken(token);
             if (appWindow != null) {
                 appWindow.startRelaunching();
@@ -5743,7 +5700,7 @@
     }
 
     public void notifyAppRelaunchingFinished(IBinder token) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final AppWindowToken appWindow = mRoot.getAppWindowToken(token);
             if (appWindow != null) {
                 appWindow.finishRelaunching();
@@ -5752,7 +5709,7 @@
     }
 
     public void notifyAppRelaunchesCleared(IBinder token) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final AppWindowToken appWindow = mRoot.getAppWindowToken(token);
             if (appWindow != null) {
                 appWindow.clearRelaunching();
@@ -5761,7 +5718,7 @@
     }
 
     public void notifyAppResumedFinished(IBinder token) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final AppWindowToken appWindow = mRoot.getAppWindowToken(token);
             if (appWindow != null) {
                 appWindow.getDisplayContent().mUnknownAppVisibilityController
@@ -5774,7 +5731,7 @@
      * Returns true if the callingUid has any window currently visible to the user.
      */
     public boolean isAnyWindowVisibleForUid(int callingUid) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             return mRoot.forAllWindows(w -> {
                 return w.getOwningUid() == callingUid && w.isVisible();
             }, true /* traverseTopToBottom */);
@@ -5788,7 +5745,7 @@
      * container may not exist when this happens.
      */
     public void notifyTaskRemovedFromRecents(int taskId, int userId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mTaskSnapshotController.notifyTaskRemovedFromRecents(taskId, userId);
         }
     }
@@ -6030,7 +5987,7 @@
         if ("apps".equals(name) || "visible".equals(name) || "visible-apps".equals(name)) {
             final boolean appsOnly = name.contains("apps");
             final boolean visibleOnly = name.contains("visible");
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 if (appsOnly) {
                     mRoot.dumpDisplayContents(pw);
                 }
@@ -6043,7 +6000,7 @@
                 }, true /* traverseTopToBottom */);
             }
         } else {
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 mRoot.getWindowsByName(windows, name);
             }
         }
@@ -6052,7 +6009,7 @@
             return false;
         }
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             dumpWindowsLocked(pw, dumpAll, windows);
         }
         return true;
@@ -6159,7 +6116,7 @@
 
         if (useProto) {
             final ProtoOutputStream proto = new ProtoOutputStream(fd);
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 writeToProtoLocked(proto, false /* trim */);
             }
             proto.flush();
@@ -6170,47 +6127,47 @@
             String cmd = args[opti];
             opti++;
             if ("lastanr".equals(cmd) || "l".equals(cmd)) {
-                synchronized(mWindowMap) {
+                synchronized (mGlobalLock) {
                     dumpLastANRLocked(pw);
                 }
                 return;
             } else if ("policy".equals(cmd) || "p".equals(cmd)) {
-                synchronized(mWindowMap) {
+                synchronized (mGlobalLock) {
                     dumpPolicyLocked(pw, args, true);
                 }
                 return;
             } else if ("animator".equals(cmd) || "a".equals(cmd)) {
-                synchronized(mWindowMap) {
+                synchronized (mGlobalLock) {
                     dumpAnimatorLocked(pw, args, true);
                 }
                 return;
             } else if ("sessions".equals(cmd) || "s".equals(cmd)) {
-                synchronized(mWindowMap) {
+                synchronized (mGlobalLock) {
                     dumpSessionsLocked(pw, true);
                 }
                 return;
             } else if ("displays".equals(cmd) || "d".equals(cmd)) {
-                synchronized(mWindowMap) {
+                synchronized (mGlobalLock) {
                     mRoot.dumpDisplayContents(pw);
                 }
                 return;
             } else if ("tokens".equals(cmd) || "t".equals(cmd)) {
-                synchronized(mWindowMap) {
+                synchronized (mGlobalLock) {
                     dumpTokensLocked(pw, true);
                 }
                 return;
             } else if ("windows".equals(cmd) || "w".equals(cmd)) {
-                synchronized(mWindowMap) {
+                synchronized (mGlobalLock) {
                     dumpWindowsLocked(pw, true, null);
                 }
                 return;
             } else if ("all".equals(cmd) || "a".equals(cmd)) {
-                synchronized(mWindowMap) {
+                synchronized (mGlobalLock) {
                     dumpWindowsLocked(pw, true, null);
                 }
                 return;
             } else if ("containers".equals(cmd)) {
-                synchronized(mWindowMap) {
+                synchronized (mGlobalLock) {
                     mRoot.dumpChildrenNames(pw, " ");
                     pw.println(" ");
                     mRoot.forAllWindows(w -> {pw.println(w);}, true /* traverseTopToBottom */);
@@ -6226,7 +6183,7 @@
             }
         }
 
-        synchronized(mWindowMap) {
+        synchronized (mGlobalLock) {
             pw.println();
             if (dumpAll) {
                 pw.println("-------------------------------------------------------------------------------");
@@ -6271,7 +6228,7 @@
     // Called by the heartbeat to ensure locks are not held indefnitely (for deadlock detection).
     @Override
     public void monitor() {
-        synchronized (mWindowMap) { }
+        synchronized (mGlobalLock) { }
     }
 
     // There is an inherent assumption that this will never return null.
@@ -6282,7 +6239,7 @@
     }
 
     public void onOverlayChanged() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mRoot.forAllDisplays(displayContent -> {
                 mPolicy.onOverlayChangedLw(displayContent);
                 displayContent.updateDisplayInfo();
@@ -6292,7 +6249,7 @@
     }
 
     public void onDisplayChanged(int displayId) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             if (displayContent != null) {
                 displayContent.updateDisplayInfo();
@@ -6303,7 +6260,7 @@
 
     @Override
     public Object getWindowManagerLock() {
-        return mWindowMap;
+        return mGlobalLock;
     }
 
     /**
@@ -6312,7 +6269,7 @@
      * @param token Application token for which the activity will be relaunched.
      */
     public void setWillReplaceWindow(IBinder token, boolean animate) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final AppWindowToken appWindowToken = mRoot.getAppWindowToken(token);
             if (appWindowToken == null) {
                 Slog.w(TAG_WM, "Attempted to set replacing window on non-existing app token "
@@ -6341,7 +6298,7 @@
     // TODO: The s at the end of the method name is the only difference with the name of the method
     // above. We should combine them or find better names.
     void setWillReplaceWindows(IBinder token, boolean childrenOnly) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final AppWindowToken appWindowToken = mRoot.getAppWindowToken(token);
             if (appWindowToken == null) {
                 Slog.w(TAG_WM, "Attempted to set replacing window on non-existing app token "
@@ -6374,7 +6331,7 @@
      * @param replacing Whether the window is being replaced or not.
      */
     public void scheduleClearWillReplaceWindows(IBinder token, boolean replacing) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final AppWindowToken appWindowToken = mRoot.getAppWindowToken(token);
             if (appWindowToken == null) {
                 Slog.w(TAG_WM, "Attempted to reset replacing window on non-existing app token "
@@ -6400,7 +6357,7 @@
 
     @Override
     public int getDockedStackSide() {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final TaskStack dockedStack = getDefaultDisplayContentLocked()
                     .getSplitScreenPrimaryStackIgnoringVisibility();
             return dockedStack == null ? DOCKED_INVALID : dockedStack.getDockSide();
@@ -6408,7 +6365,7 @@
     }
 
     public void setDockedStackResizing(boolean resizing) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             getDefaultDisplayContentLocked().getDockedDividerController().setResizing(resizing);
             requestTraversal();
         }
@@ -6416,7 +6373,7 @@
 
     @Override
     public void setDockedStackDividerTouchRegion(Rect touchRegion) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent dc = getDefaultDisplayContentLocked();
             dc.getDockedDividerController().setTouchRegion(touchRegion);
             dc.updateTouchExcludeRegion();
@@ -6425,32 +6382,32 @@
 
     @Override
     public void setResizeDimLayer(boolean visible, int targetWindowingMode, float alpha) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             getDefaultDisplayContentLocked().getDockedDividerController().setResizeDimLayer(
                     visible, targetWindowingMode, alpha);
         }
     }
 
     public void setForceResizableTasks(boolean forceResizableTasks) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mForceResizableTasks = forceResizableTasks;
         }
     }
 
     public void setSupportsPictureInPicture(boolean supportsPictureInPicture) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mSupportsPictureInPicture = supportsPictureInPicture;
         }
     }
 
     public void setSupportsFreeformWindowManagement(boolean supportsFreeformWindowManagement) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mSupportsFreeformWindowManagement = supportsFreeformWindowManagement;
         }
     }
 
     public void setIsPc(boolean isPc) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mIsPc = isPc;
         }
     }
@@ -6463,7 +6420,7 @@
     public void registerDockedStackListener(IDockedStackListener listener) {
         mAtmInternal.enforceCallerIsRecentsOrHasPermission(REGISTER_WINDOW_MANAGER_LISTENERS,
                 "registerDockedStackListener()");
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             // TODO(multi-display): The listener is registered on the default display only.
             getDefaultDisplayContentLocked().mDividerControllerLocked.registerDockedStackListener(
                     listener);
@@ -6479,7 +6436,7 @@
         if (!mSupportsPictureInPicture) {
             return;
         }
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
             displayContent.getPinnedStackController().registerPinnedStackListener(listener);
         }
@@ -6498,7 +6455,7 @@
 
     @Override
     public void getStableInsets(int displayId, Rect outInsets) throws RemoteException {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             getStableInsetsLocked(displayId, outInsets);
         }
     }
@@ -6557,7 +6514,7 @@
             mouseY = mMousePositionTracker.mLatestMouseY;
         }
 
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mDragDropController.dragDropActiveLocked()) {
                 // Drag cursor overrides the app cursor.
                 return;
@@ -6612,7 +6569,7 @@
      */
     void updateTapExcludeRegion(IWindow client, int regionId, int left, int top, int width,
             int height) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             final WindowState callingWin = windowForClientLocked(null, client, false);
             if (callingWin == null) {
                 Slog.w(TAG_WM, "Bad requesting window " + client);
@@ -6626,7 +6583,7 @@
     public void dontOverrideDisplayInfo(int displayId) {
         final long token = Binder.clearCallingIdentity();
         try {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent dc = getDisplayContentOrCreate(displayId, null);
                 if (dc == null) {
                     throw new IllegalArgumentException(
@@ -6692,7 +6649,7 @@
 
         @Override
         public void setMagnificationSpec(MagnificationSpec spec) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 if (mAccessibilityController != null) {
                     mAccessibilityController.setMagnificationSpecLocked(spec);
                 } else {
@@ -6706,7 +6663,7 @@
 
         @Override
         public void setForceShowMagnifiableBounds(boolean show) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 if (mAccessibilityController != null) {
                     mAccessibilityController.setForceShowMagnifiableBoundsLocked(show);
                 } else {
@@ -6717,7 +6674,7 @@
 
         @Override
         public void getMagnificationRegion(@NonNull Region magnificationRegion) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 if (mAccessibilityController != null) {
                     mAccessibilityController.getMagnificationRegionLocked(magnificationRegion);
                 } else {
@@ -6728,7 +6685,7 @@
 
         @Override
         public MagnificationSpec getCompatibleMagnificationSpecForWindow(IBinder windowToken) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 WindowState windowState = mWindowMap.get(windowToken);
                 if (windowState == null) {
                     return null;
@@ -6748,7 +6705,7 @@
 
         @Override
         public void setMagnificationCallbacks(@Nullable MagnificationCallbacks callbacks) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 if (mAccessibilityController == null) {
                     mAccessibilityController = new AccessibilityController(
                             WindowManagerService.this);
@@ -6762,7 +6719,7 @@
 
         @Override
         public void setWindowsForAccessibilityCallback(WindowsForAccessibilityCallback callback) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 if (mAccessibilityController == null) {
                     mAccessibilityController = new AccessibilityController(
                             WindowManagerService.this);
@@ -6781,7 +6738,7 @@
 
         @Override
         public IBinder getFocusedWindowToken() {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 WindowState windowState = getFocusedWindowLocked();
                 if (windowState != null) {
                     return windowState.mClient.asBinder();
@@ -6807,7 +6764,7 @@
 
         @Override
         public void getWindowFrame(IBinder token, Rect outBounds) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 WindowState windowState = mWindowMap.get(token);
                 if (windowState != null) {
                     outBounds.set(windowState.getFrameLw());
@@ -6820,7 +6777,7 @@
         @Override
         public void waitForAllWindowsDrawn(Runnable callback, long timeout) {
             boolean allWindowsDrawn = false;
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 mWaitingForDrawnCallback = callback;
                 getDefaultDisplayContentLocked().waitForAllWindowsDrawn();
                 mWindowPlacerLocked.requestTraversal();
@@ -6844,7 +6801,7 @@
 
         @Override
         public void removeWindowToken(IBinder binder, boolean removeWindows, int displayId) {
-            synchronized(mWindowMap) {
+            synchronized (mGlobalLock) {
                 if (removeWindows) {
                     final DisplayContent dc = mRoot.getDisplayContent(displayId);
                     if (dc == null) {
@@ -6870,14 +6827,14 @@
         // forwarding it to SystemUI for synchronizing status and navigation bar animations.
         @Override
         public void registerAppTransitionListener(AppTransitionListener listener) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 getDefaultDisplayContentLocked().mAppTransition.registerListenerLocked(listener);
             }
         }
 
         @Override
         public int getInputMethodWindowVisibleHeight(int displayId) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent dc = mRoot.getDisplayContent(displayId);
                 return dc.mDisplayFrames.getInputMethodWindowVisibleHeight();
             }
@@ -6901,7 +6858,7 @@
 
         @Override
         public boolean isHardKeyboardAvailable() {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 return mHardKeyboardAvailable;
             }
         }
@@ -6909,14 +6866,14 @@
         @Override
         public void setOnHardKeyboardStatusChangeListener(
                 OnHardKeyboardStatusChangeListener listener) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 mHardKeyboardStatusChangeListener = listener;
             }
         }
 
         @Override
         public boolean isStackVisible(int windowingMode) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent dc = getDefaultDisplayContentLocked();
                 return dc.isStackVisible(windowingMode);
             }
@@ -6924,7 +6881,7 @@
 
         @Override
         public boolean isDockedDividerResizing() {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 return getDefaultDisplayContentLocked().getDockedDividerController().isResizing();
             }
         }
@@ -6932,7 +6889,7 @@
         @Override
         public void computeWindowsForAccessibility() {
             final AccessibilityController accessibilityController;
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 accessibilityController = mAccessibilityController;
             }
             if (accessibilityController != null) {
@@ -6962,7 +6919,7 @@
 
         @Override
         public int getWindowOwnerUserId(IBinder token) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 WindowState window = mWindowMap.get(token);
                 if (window != null) {
                     return UserHandle.getUserId(window.mOwnerUid);
@@ -6973,7 +6930,7 @@
 
         @Override
         public boolean isUidFocused(int uid) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 for (int i = mRoot.getChildCount() - 1; i >= 0; i--) {
                     final DisplayContent displayContent = mRoot.getChildAt(i);
                     if (displayContent.mCurrentFocus != null
@@ -6990,7 +6947,7 @@
             if (displayId == Display.INVALID_DISPLAY) {
                 return false;
             }
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent displayContent = mRoot.getTopFocusedDisplayContent();
                 if (displayContent == null
                         || displayContent.getDisplayId() != displayId
@@ -7025,7 +6982,7 @@
             if (displayId == Display.INVALID_DISPLAY) {
                 return false;
             }
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 final DisplayContent displayContent = mRoot.getDisplayContent(displayId);
                 return displayContent != null && displayContent.hasAccess(uid);
             }
@@ -7033,7 +6990,7 @@
 
         @Override
         public int getDisplayIdForWindow(IBinder windowToken) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 final WindowState window = mWindowMap.get(windowToken);
                 if (window != null) {
                     return window.getDisplayContent().getDisplayId();
@@ -7044,7 +7001,7 @@
 
         @Override
         public void onProcessConfigurationChanged(int pid, Configuration newConfig) {
-            synchronized (mWindowMap) {
+            synchronized (mGlobalLock) {
                 Configuration currentConfig = mProcessConfigurations.get(pid);
                 if (currentConfig == null) {
                     currentConfig = new Configuration(newConfig);
@@ -7100,7 +7057,7 @@
         // The client depends on us to have resized the surface
         // by that point (b/36462635)
 
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             SurfaceControl.openTransaction();
             try {
                 exec.run();
@@ -7112,7 +7069,7 @@
 
     /** Called to inform window manager if non-Vr UI shoul be disabled or not. */
     public void disableNonVrUi(boolean disable) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             // Allow alert window notifications to be shown if non-vr UI is enabled.
             final boolean showAlertWindowNotifications = !disable;
             if (showAlertWindowNotifications == mShowAlertWindowNotifications) {
@@ -7196,7 +7153,7 @@
      *                      {@link ActivityManager#LOCK_TASK_MODE_PINNED}.
      */
     public void onLockTaskStateChanged(int lockTaskState) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             mPolicy.onLockTaskStateChangedLw(lockTaskState);
         }
     }
@@ -7207,7 +7164,7 @@
      * ensure the new value takes effect.
      */
     public void setAodShowing(boolean aodShowing) {
-        synchronized (mWindowMap) {
+        synchronized (mGlobalLock) {
             if (mPolicy.setAodShowing(aodShowing)) {
                 mWindowPlacerLocked.performSurfacePlacement();
             }
diff --git a/services/core/java/com/android/server/am/WindowProcessController.java b/services/core/java/com/android/server/wm/WindowProcessController.java
similarity index 95%
rename from services/core/java/com/android/server/am/WindowProcessController.java
rename to services/core/java/com/android/server/wm/WindowProcessController.java
index 1dd8c52..bb17254 100644
--- a/services/core/java/com/android/server/am/WindowProcessController.java
+++ b/services/core/java/com/android/server/wm/WindowProcessController.java
@@ -14,28 +14,28 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.PROCESS_STATE_NONEXISTENT;
 import static android.view.Display.INVALID_DISPLAY;
 
 import static com.android.server.am.ActivityManagerService.MY_PID;
-import static com.android.server.am.ActivityStack.ActivityState.DESTROYED;
-import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
-import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
-import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.DEBUG_RELEASE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.POSTFIX_RELEASE;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_ATM;
-import static com.android.server.am.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
-import static com.android.server.am.ActivityTaskManagerService
+import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED;
+import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSED;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSING;
+import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
+import static com.android.server.wm.ActivityStack.ActivityState.STOPPING;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_RELEASE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_CONFIGURATION;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_RELEASE;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM;
+import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME;
+import static com.android.server.wm.ActivityTaskManagerService
         .INSTRUMENTATION_KEY_DISPATCHING_TIMEOUT_MS;
-import static com.android.server.am.ActivityTaskManagerService.KEY_DISPATCHING_TIMEOUT_MS;
-import static com.android.server.am.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
+import static com.android.server.wm.ActivityTaskManagerService.KEY_DISPATCHING_TIMEOUT_MS;
+import static com.android.server.wm.ActivityTaskManagerService.RELAUNCH_REASON_NONE;
 
 import android.app.Activity;
 import android.app.ActivityThread;
@@ -55,17 +55,15 @@
 import com.android.internal.app.HeavyWeightSwitcherActivity;
 import com.android.internal.util.function.pooled.PooledLambda;
 import com.android.server.Watchdog;
-import com.android.server.wm.ConfigurationContainer;
-import com.android.server.wm.ConfigurationContainerListener;
 
 import java.io.PrintWriter;
 import java.util.ArrayList;
 
 /**
  * The Activity Manager (AM) package manages the lifecycle of processes in the system through
- * {@link ProcessRecord}. However, it is important for the Window Manager (WM) package to be aware
+ * ProcessRecord. However, it is important for the Window Manager (WM) package to be aware
  * of the processes and their state since it affects how WM manages windows and activities. This
- * class that allows the {@link ProcessRecord} object in the AM package to communicate important
+ * class that allows the ProcessRecord object in the AM package to communicate important
  * changes to its state to the WM package in a structured way. WM package also uses
  * {@link WindowProcessListener} to request changes to the process state on the AM side.
  * Note that public calls into this class are assumed to be originating from outside the
@@ -156,8 +154,8 @@
     // Registered display id as a listener to override config change
     private int mDisplayId;
 
-    WindowProcessController(ActivityTaskManagerService atm, ApplicationInfo info, String name,
-            int uid, int userId, Object owner, WindowProcessListener listener) {
+    public WindowProcessController(ActivityTaskManagerService atm, ApplicationInfo info,
+            String name, int uid, int userId, Object owner, WindowProcessListener listener) {
         mInfo = info;
         mName = name;
         mUid = uid;
@@ -176,7 +174,7 @@
         mPid = pid;
     }
 
-    int getPid() {
+    public int getPid() {
         return mPid;
     }
 
@@ -622,7 +620,7 @@
         return minTaskLayer;
     }
 
-    int computeRelaunchReason() {
+    public int computeRelaunchReason() {
         synchronized (mAtm.mGlobalLock) {
             final int activitiesSize = mActivities.size();
             for (int i = activitiesSize - 1; i >= 0; i--) {
diff --git a/services/core/java/com/android/server/am/WindowProcessListener.java b/services/core/java/com/android/server/wm/WindowProcessListener.java
similarity index 96%
rename from services/core/java/com/android/server/am/WindowProcessListener.java
rename to services/core/java/com/android/server/wm/WindowProcessListener.java
index 4a7e6e8..7f20f4b 100644
--- a/services/core/java/com/android/server/am/WindowProcessListener.java
+++ b/services/core/java/com/android/server/wm/WindowProcessListener.java
@@ -14,10 +14,9 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import android.app.ProfilerInfo;
-import android.content.pm.ApplicationInfo;
 import android.util.proto.ProtoOutputStream;
 
 /**
diff --git a/services/core/java/com/android/server/wm/WindowState.java b/services/core/java/com/android/server/wm/WindowState.java
index 9dc7721..99f65c3 100644
--- a/services/core/java/com/android/server/wm/WindowState.java
+++ b/services/core/java/com/android/server/wm/WindowState.java
@@ -103,7 +103,6 @@
 import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_WALLPAPER_LIGHT;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WITH_CLASS_NAME;
 import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM;
-import static com.android.server.wm.WindowManagerService.H.SEND_NEW_CONFIGURATION;
 import static com.android.server.wm.WindowManagerService.MAX_ANIMATION_DURATION;
 import static com.android.server.wm.WindowManagerService.TYPE_LAYER_MULTIPLIER;
 import static com.android.server.wm.WindowManagerService.TYPE_LAYER_OFFSET;
@@ -1942,8 +1941,11 @@
             removeImmediately();
             // Removing a visible window will effect the computed orientation
             // So just update orientation if needed.
-            if (wasVisible && mService.updateOrientationFromAppTokensLocked(displayId)) {
-                mService.mH.obtainMessage(SEND_NEW_CONFIGURATION, displayId).sendToTarget();
+            if (wasVisible) {
+                final DisplayContent displayContent = getDisplayContent();
+                if (displayContent.updateOrientationFromAppTokens()) {
+                    displayContent.sendNewConfiguration();
+                }
             }
             mService.updateFocusedWindowLocked(isFocused()
                             ? UPDATE_FOCUS_REMOVING_FOCUS
@@ -2314,7 +2316,7 @@
         public void binderDied() {
             try {
                 boolean resetSplitScreenResizing = false;
-                synchronized(mService.mWindowMap) {
+                synchronized (mService.mGlobalLock) {
                     final WindowState win = mService.windowForClientLocked(mSession, mClient, false);
                     Slog.i(TAG, "WIN DEATH: " + win);
                     if (win != null) {
@@ -2984,7 +2986,7 @@
     }
 
     public void registerFocusObserver(IWindowFocusObserver observer) {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             if (mFocusCallbacks == null) {
                 mFocusCallbacks = new RemoteCallbackList<IWindowFocusObserver>();
             }
@@ -2993,7 +2995,7 @@
     }
 
     public void unregisterFocusObserver(IWindowFocusObserver observer) {
-        synchronized(mService.mWindowMap) {
+        synchronized (mService.mGlobalLock) {
             if (mFocusCallbacks != null) {
                 mFocusCallbacks.unregister(observer);
             }
@@ -4440,7 +4442,7 @@
         public boolean isFocused() {
             final WindowState outer = mOuter.get();
             if (outer != null) {
-                synchronized (outer.mService.mWindowMap) {
+                synchronized (outer.mService.mGlobalLock) {
                     return outer.isFocused();
                 }
             }
diff --git a/services/core/java/com/android/server/wm/WindowSurfacePlacer.java b/services/core/java/com/android/server/wm/WindowSurfacePlacer.java
index e82ffe8..7d25b8c 100644
--- a/services/core/java/com/android/server/wm/WindowSurfacePlacer.java
+++ b/services/core/java/com/android/server/wm/WindowSurfacePlacer.java
@@ -61,7 +61,7 @@
         mService = service;
         mWallpaperControllerLocked = mService.mRoot.mWallpaperController;
         mPerformSurfacePlacement = () -> {
-            synchronized (mService.mWindowMap) {
+            synchronized (mService.mGlobalLock) {
                 performSurfacePlacement();
             }
         };
diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/NetworkLogger.java b/services/devicepolicy/java/com/android/server/devicepolicy/NetworkLogger.java
index 4514492..e9b2d7f 100644
--- a/services/devicepolicy/java/com/android/server/devicepolicy/NetworkLogger.java
+++ b/services/devicepolicy/java/com/android/server/devicepolicy/NetworkLogger.java
@@ -53,8 +53,8 @@
 
     private final INetdEventCallback mNetdEventCallback = new BaseNetdEventCallback() {
         @Override
-        public void onDnsEvent(String hostname, String[] ipAddresses, int ipAddressesCount,
-                long timestamp, int uid) {
+        public void onDnsEvent(int netId, int eventType, int returnCode, String hostname,
+                String[] ipAddresses, int ipAddressesCount, long timestamp, int uid) {
             if (!mIsLoggingEnabled.get()) {
                 return;
             }
diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java
index b1b5a7a..49f410d 100644
--- a/services/java/com/android/server/SystemServer.java
+++ b/services/java/com/android/server/SystemServer.java
@@ -64,7 +64,7 @@
 import com.android.internal.util.EmergencyAffordanceManager;
 import com.android.internal.widget.ILockSettings;
 import com.android.server.am.ActivityManagerService;
-import com.android.server.am.ActivityTaskManagerService;
+import com.android.server.wm.ActivityTaskManagerService;
 import com.android.server.appbinding.AppBindingService;
 import com.android.server.audio.AudioService;
 import com.android.server.biometrics.BiometricService;
diff --git a/services/tests/servicestests/AndroidManifest.xml b/services/tests/servicestests/AndroidManifest.xml
index 863e487..fa17b61 100644
--- a/services/tests/servicestests/AndroidManifest.xml
+++ b/services/tests/servicestests/AndroidManifest.xml
@@ -206,11 +206,11 @@
             </intent-filter>
         </activity-alias>
 
-        <activity android:name="com.android.server.am.TaskStackChangedListenerTest$ActivityA" />
-        <activity android:name="com.android.server.am.TaskStackChangedListenerTest$ActivityB" />
-        <activity android:name="com.android.server.am.TaskStackChangedListenerTest$ActivityRequestedOrientationChange" />
-        <activity android:name="com.android.server.am.TaskStackChangedListenerTest$ActivityTaskChangeCallbacks" />
-        <activity android:name="com.android.server.am.TaskStackChangedListenerTest$ActivityTaskDescriptionChange" />
+        <activity android:name="com.android.server.wm.TaskStackChangedListenerTest$ActivityA" />
+        <activity android:name="com.android.server.wm.TaskStackChangedListenerTest$ActivityB" />
+        <activity android:name="com.android.server.wm.TaskStackChangedListenerTest$ActivityRequestedOrientationChange" />
+        <activity android:name="com.android.server.wm.TaskStackChangedListenerTest$ActivityTaskChangeCallbacks" />
+        <activity android:name="com.android.server.wm.TaskStackChangedListenerTest$ActivityTaskDescriptionChange" />
 
         <receiver android:name="com.android.server.appwidget.DummyAppWidget">
             <intent-filter>
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityManagerInternalTest.java b/services/tests/servicestests/src/com/android/server/am/ActivityManagerInternalTest.java
index 8c27e25..e4fe599 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityManagerInternalTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/ActivityManagerInternalTest.java
@@ -11,7 +11,7 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
 package com.android.server.am;
@@ -23,30 +23,18 @@
 import android.os.SystemClock;
 
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
 /**
  * Test class for {@link ActivityManagerInternal}.
  *
- * To run the tests, use
- *
- * runtest -c com.android.server.am.ActivityManagerInternalTest frameworks-services
- *
- * or the following steps:
- *
- * Build: m FrameworksServicesTests
- * Install: adb install -r \
- *     ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk
- * Run: adb shell am instrument -e class com.android.server.am.ActivityManagerInternalTest -w \
- *     com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
+ * Build/Install/Run:
+ *  atest FrameworksServicesTests:ActivityManagerInternalTest
  */
-@RunWith(AndroidJUnit4.class)
 public class ActivityManagerInternalTest {
     private static final int TEST_UID1 = 111;
     private static final int TEST_UID2 = 112;
@@ -59,6 +47,7 @@
 
     private ActivityManagerService mAms;
     private ActivityManagerInternal mAmi;
+
     @Before
     public void setUp() {
         MockitoAnnotations.initMocks(this);
@@ -147,18 +136,19 @@
 
         private final Object mLock;
         private Runnable mRunnable;
-        boolean mNotified;
+        public boolean mNotified;
 
-        public CustomThread(Object lock) {
+        CustomThread(Object lock) {
             mLock = lock;
         }
 
-        public CustomThread(Object lock, Runnable runnable) {
+        CustomThread(Object lock, Runnable runnable) {
             super(runnable);
             mLock = lock;
             mRunnable = runnable;
         }
 
+        @SuppressWarnings("WaitNotInLoop")
         @Override
         public void run() {
             if (mRunnable != null) {
@@ -168,7 +158,7 @@
                     try {
                         mLock.wait();
                     } catch (InterruptedException e) {
-                        Thread.currentThread().interrupted();
+                        Thread.interrupted();
                     }
                 }
             }
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java
index 060c55d..767eb60 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/ActivityManagerServiceTest.java
@@ -11,7 +11,7 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
 package com.android.server.am;
@@ -67,14 +67,12 @@
 import androidx.test.filters.FlakyTest;
 import androidx.test.filters.MediumTest;
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import com.android.server.AppOpsService;
 
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
@@ -90,21 +88,11 @@
 /**
  * Test class for {@link ActivityManagerService}.
  *
- * To run the tests, use
- *
- * runtest -c com.android.server.am.ActivityManagerServiceTest frameworks-services
- *
- * or the following steps:
- *
- * Build: m FrameworksServicesTests
- * Install: adb install -r \
- *     ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk
- * Run: adb shell am instrument -e class com.android.server.am.ActivityManagerServiceTest -w \
- *     com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
+ * Build/Install/Run:
+ *  atest FrameworksServicesTests:ActivityManagerServiceTest
  */
 @SmallTest
 @FlakyTest(bugId = 113616538)
-@RunWith(AndroidJUnit4.class)
 public class ActivityManagerServiceTest {
     private static final String TAG = ActivityManagerServiceTest.class.getSimpleName();
 
@@ -149,6 +137,7 @@
         mHandlerThread.quit();
     }
 
+    @SuppressWarnings("GuardedBy")
     @MediumTest
     @Test
     public void incrementProcStateSeqAndNotifyAppsLocked() throws Exception {
@@ -175,6 +164,7 @@
                 true); // expectNotify
 
         // Explicitly setting the seq counter for more verification.
+        // @SuppressWarnings("GuardedBy")
         mAms.mProcessList.mProcStateSeqCounter = 42;
 
         // Uid state is not moving from background to foreground or vice versa.
@@ -267,6 +257,7 @@
         return uidRec;
     }
 
+    @SuppressWarnings("GuardedBy")
     private void verifySeqCounterAndInteractions(UidRecord uidRec, int prevState, int curState,
             int expectedGlobalCounter, int expectedCurProcStateSeq, int expectedBlockState,
             boolean expectNotify) throws Exception {
@@ -277,6 +268,7 @@
         uidRec.setCurProcState(curState);
         mAms.incrementProcStateSeqAndNotifyAppsLocked();
 
+        // @SuppressWarnings("GuardedBy")
         assertEquals(expectedGlobalCounter, mAms.mProcessList.mProcStateSeqCounter);
         assertEquals(expectedCurProcStateSeq, uidRec.curProcStateSeq);
 
@@ -561,8 +553,8 @@
             ActivityManager.PROCESS_STATE_SERVICE,
             ActivityManager.PROCESS_STATE_RECEIVER
         };
-        final ArrayList<UidRecord.ChangeItem> pendingItemsForUids
-                = new ArrayList<>(changesForPendingItems.length);
+        final ArrayList<UidRecord.ChangeItem> pendingItemsForUids =
+                new ArrayList<>(changesForPendingItems.length);
         for (int i = 0; i < changesForPendingItems.length; ++i) {
             final UidRecord.ChangeItem item = new UidRecord.ChangeItem();
             item.uid = i;
@@ -621,7 +613,7 @@
         }
         mAms.mPendingUidChanges.addAll(pendingItemsForUids);
         mAms.dispatchUidsChanged();
-        assertEquals("validateUids should be empty, validateUids: " + mAms.mValidateUids,
+        assertEquals("validateUids should be empty, size=" + mAms.mValidateUids.size(),
                 0, mAms.mValidateUids.size());
     }
 
@@ -775,7 +767,7 @@
         mAms.mActiveUids.clear();
     }
 
-    private class TestHandler extends Handler {
+    private static class TestHandler extends Handler {
         private static final long WAIT_FOR_MSG_TIMEOUT_MS = 4000; // 4 sec
         private static final long WAIT_FOR_MSG_INTERVAL_MS = 400; // 0.4 sec
 
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityManagerTest.java b/services/tests/servicestests/src/com/android/server/am/ActivityManagerTest.java
index 2dfb375..8965152 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityManagerTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/ActivityManagerTest.java
@@ -27,33 +27,33 @@
 import android.os.UserHandle;
 import android.platform.test.annotations.Presubmit;
 
+import androidx.test.filters.FlakyTest;
+
 import org.junit.Before;
 import org.junit.Test;
 
 import java.util.List;
 
-import androidx.test.filters.FlakyTest;
-
 /**
  * Tests for {@link ActivityManager}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:com.android.server.am.ActivityManagerTest
+ *  atest FrameworksServicesTests:ActivityManagerTest
  */
-@Presubmit
 @FlakyTest(detail = "Promote to presubmit if stable")
+@Presubmit
 public class ActivityManagerTest {
 
-    private IActivityManager service;
+    private IActivityManager mService;
 
     @Before
     public void setUp() throws Exception {
-        service = ActivityManager.getService();
+        mService = ActivityManager.getService();
     }
 
     @Test
     public void testTaskIdsForRunningUsers() throws RemoteException {
-        int[] runningUserIds = service.getRunningUserIds();
+        int[] runningUserIds = mService.getRunningUserIds();
         assertThat(runningUserIds).isNotEmpty();
         for (int userId : runningUserIds) {
             testTaskIdsForUser(userId);
@@ -61,7 +61,7 @@
     }
 
     private void testTaskIdsForUser(int userId) throws RemoteException {
-        List<?> recentTasks = service.getRecentTasks(100, 0, userId).getList();
+        List<?> recentTasks = mService.getRecentTasks(100, 0, userId).getList();
         if (recentTasks != null) {
             for (Object elem : recentTasks) {
                 assertThat(elem).isInstanceOf(RecentTaskInfo.class);
diff --git a/services/tests/servicestests/src/com/android/server/am/AppErrorDialogTest.java b/services/tests/servicestests/src/com/android/server/am/AppErrorDialogTest.java
index 3a7a24d..05cb48b 100644
--- a/services/tests/servicestests/src/com/android/server/am/AppErrorDialogTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/AppErrorDialogTest.java
@@ -16,27 +16,26 @@
 
 package com.android.server.am;
 
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
 import android.content.Context;
 import android.os.Handler;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.annotation.UiThreadTest;
 import androidx.test.filters.FlakyTest;
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import com.android.server.AppOpsService;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.io.File;
 
 /**
- * runtest -c com.android.server.am.AppErrorDialogTest frameworks-services
+ * Build/Install/Run:
+ *  atest FrameworksServicesTests:AppErrorDialogTest
  */
-@RunWith(AndroidJUnit4.class)
 @SmallTest
 @FlakyTest(bugId = 113616538)
 public class AppErrorDialogTest {
@@ -46,7 +45,7 @@
 
     @Before
     public void setUp() throws Exception {
-        mContext = InstrumentationRegistry.getTargetContext();
+        mContext = getInstrumentation().getTargetContext();
         mService = new ActivityManagerService(new ActivityManagerService.Injector() {
             @Override
             public AppOpsService getAppOpsService(File file, Handler handler) {
@@ -67,7 +66,7 @@
 
     @Test
     @UiThreadTest
-    public void testCreateWorks() throws Exception {
+    public void testCreateWorks() {
         AppErrorDialog.Data data = new AppErrorDialog.Data();
         data.proc = new ProcessRecord(null, mContext.getApplicationInfo(), "name", 12345);
         data.result = new AppErrorResult();
diff --git a/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java b/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java
index 75f7c4c..0889265 100644
--- a/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/BroadcastRecordTest.java
@@ -27,10 +27,8 @@
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -40,11 +38,10 @@
  * Test class for {@link BroadcastRecord}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:com.android.server.am.BroadcastRecordTest
+ *  atest FrameworksServicesTests:BroadcastRecordTest
  */
 @SmallTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class BroadcastRecordTest {
 
     @Test
diff --git a/services/tests/servicestests/src/com/android/server/am/CoreSettingsObserverTest.java b/services/tests/servicestests/src/com/android/server/am/CoreSettingsObserverTest.java
index 719e0ed..9626990 100644
--- a/services/tests/servicestests/src/com/android/server/am/CoreSettingsObserverTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/CoreSettingsObserverTest.java
@@ -11,15 +11,18 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
 package com.android.server.am;
 
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
 import static com.android.server.am.ActivityManagerService.Injector;
 
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
 import static org.mockito.Mockito.when;
 
 import android.content.Context;
@@ -28,9 +31,7 @@
 import android.provider.Settings;
 import android.test.mock.MockContentResolver;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.util.test.FakeSettingsProvider;
 import com.android.server.AppOpsService;
@@ -39,7 +40,6 @@
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
@@ -48,20 +48,10 @@
 /**
  * Test class for {@link CoreSettingsObserver}.
  *
- * To run the tests, use
- *
- * runtest -c com.android.server.am.CoreSettingsObserverTest frameworks-services
- *
- * or the following steps:
- *
- * Build: m FrameworksServicesTests
- * Install: adb install -r \
- *     ${ANDROID_PRODUCT_OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk
- * Run: adb shell am instrument -e class com.android.server.am.CoreSettingsObserverTest -w \
- *     com.android.frameworks.servicestests/androidx.test.runner.AndroidJUnitRunner
+ * Build/Install/Run:
+ *  atest FrameworksServicesTests:CoreSettingsObserverTest
  */
 @SmallTest
-@RunWith(AndroidJUnit4.class)
 public class CoreSettingsObserverTest {
     private static final String TEST_SETTING_SECURE_INT = "secureInt";
     private static final String TEST_SETTING_GLOBAL_FLOAT = "globalFloat";
@@ -94,7 +84,7 @@
     public void setUp() {
         MockitoAnnotations.initMocks(this);
 
-        final Context originalContext = InstrumentationRegistry.getContext();
+        final Context originalContext = getInstrumentation().getTargetContext();
         when(mContext.getApplicationInfo()).thenReturn(originalContext.getApplicationInfo());
         mContentResolver = new MockContentResolver(mContext);
         mContentResolver.addProvider(Settings.AUTHORITY, new FakeSettingsProvider());
@@ -124,12 +114,12 @@
     public void testPopulateSettings_settingNotSet() {
         final Bundle settingsBundle = getPopulatedBundle();
 
-        assertFalse("Bundle should not contain " + TEST_SETTING_SECURE_INT,
-                settingsBundle.containsKey(TEST_SETTING_SECURE_INT));
-        assertFalse("Bundle should not contain " + TEST_SETTING_GLOBAL_FLOAT,
-                settingsBundle.containsKey(TEST_SETTING_GLOBAL_FLOAT));
-        assertFalse("Bundle should not contain " + TEST_SETTING_SYSTEM_STRING,
-                settingsBundle.containsKey(TEST_SETTING_SYSTEM_STRING));
+        assertWithMessage("Bundle should not contain " + TEST_SETTING_SECURE_INT)
+                .that(settingsBundle.keySet()).doesNotContain(TEST_SETTING_SECURE_INT);
+        assertWithMessage("Bundle should not contain " + TEST_SETTING_GLOBAL_FLOAT)
+                .that(settingsBundle.keySet()).doesNotContain(TEST_SETTING_GLOBAL_FLOAT);
+        assertWithMessage("Bundle should not contain " + TEST_SETTING_SYSTEM_STRING)
+                .that(settingsBundle.keySet()).doesNotContain(TEST_SETTING_SYSTEM_STRING);
     }
 
     @Test
@@ -150,8 +140,8 @@
         Settings.Global.putString(mContentResolver, TEST_SETTING_GLOBAL_FLOAT, null);
         settingsBundle = getPopulatedBundle();
 
-        assertFalse("Bundle should not contain " + TEST_SETTING_GLOBAL_FLOAT,
-                settingsBundle.containsKey(TEST_SETTING_GLOBAL_FLOAT));
+        assertWithMessage("Bundle should not contain " + TEST_SETTING_GLOBAL_FLOAT)
+                .that(settingsBundle.keySet()).doesNotContain(TEST_SETTING_GLOBAL_FLOAT);
         assertEquals("Unexpected value of " + TEST_SETTING_SECURE_INT,
                 TEST_INT, settingsBundle.getInt(TEST_SETTING_SECURE_INT));
         assertEquals("Unexpected value of " + TEST_SETTING_SYSTEM_STRING,
@@ -170,6 +160,7 @@
             return mContext;
         }
 
+        @Override
         public AppOpsService getAppOpsService(File file, Handler handler) {
             return null;
         }
diff --git a/services/tests/servicestests/src/com/android/server/am/GlobalSettingsToPropertiesMapperTest.java b/services/tests/servicestests/src/com/android/server/am/GlobalSettingsToPropertiesMapperTest.java
index 765aaad..c162c3b 100644
--- a/services/tests/servicestests/src/com/android/server/am/GlobalSettingsToPropertiesMapperTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/GlobalSettingsToPropertiesMapperTest.java
@@ -11,34 +11,37 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
 package com.android.server.am;
 
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
 import android.content.ContentResolver;
 import android.provider.Settings;
 import android.test.mock.MockContentResolver;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.util.Preconditions;
 import com.android.internal.util.test.FakeSettingsProvider;
 
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.HashMap;
 import java.util.Map;
 
 /**
  * Tests for {@link GlobalSettingsToPropertiesMapper}
+ *
+ * Build/Install/Run:
+ *  atest FrameworksServicesTests:GlobalSettingsToPropertiesMapperTest
  */
-@RunWith(AndroidJUnit4.class)
 @SmallTest
 public class GlobalSettingsToPropertiesMapperTest {
     private static final String[][] TEST_MAPPING = new String[][] {
@@ -51,7 +54,7 @@
     @Before
     public void setup() {
         // Use FakeSettingsProvider to not affect global state
-        mMockContentResolver = new MockContentResolver(InstrumentationRegistry.getContext());
+        mMockContentResolver = new MockContentResolver(getInstrumentation().getTargetContext());
         mMockContentResolver.addProvider(Settings.AUTHORITY, new FakeSettingsProvider());
         mTestMapper = new TestMapper(mMockContentResolver);
     }
@@ -63,21 +66,21 @@
 
         mTestMapper.updatePropertiesFromGlobalSettings();
         String propValue = mTestMapper.systemPropertiesGet("TestProperty");
-        Assert.assertEquals("testValue", propValue);
+        assertEquals("testValue", propValue);
 
         Settings.Global.putString(mMockContentResolver,
                 Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, "testValue2");
         mTestMapper.updatePropertyFromSetting(Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS,
                 "TestProperty");
         propValue = mTestMapper.systemPropertiesGet("TestProperty");
-        Assert.assertEquals("testValue2", propValue);
+        assertEquals("testValue2", propValue);
 
         Settings.Global.putString(mMockContentResolver,
                 Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS, null);
         mTestMapper.updatePropertyFromSetting(Settings.Global.SQLITE_COMPATIBILITY_WAL_FLAGS,
                 "TestProperty");
         propValue = mTestMapper.systemPropertiesGet("TestProperty");
-        Assert.assertEquals("", propValue);
+        assertEquals("", propValue);
     }
 
     @Test
@@ -85,7 +88,7 @@
         // Test that empty property will not not be set if setting is not set
         mTestMapper.updatePropertiesFromGlobalSettings();
         String propValue = mTestMapper.systemPropertiesGet("TestProperty");
-        Assert.assertNull("Property should not be set if setting is null", propValue);
+        assertNull("Property should not be set if setting is null", propValue);
     }
 
     private static class TestMapper extends GlobalSettingsToPropertiesMapper {
@@ -108,6 +111,5 @@
             mProps.put(key, value);
         }
     }
-
 }
 
diff --git a/services/tests/servicestests/src/com/android/server/am/MemoryStatUtilTest.java b/services/tests/servicestests/src/com/android/server/am/MemoryStatUtilTest.java
index 72c5b10..c7409d7 100644
--- a/services/tests/servicestests/src/com/android/server/am/MemoryStatUtilTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/MemoryStatUtilTest.java
@@ -29,14 +29,15 @@
 import static org.junit.Assert.assertNull;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.Collections;
 
-@RunWith(AndroidJUnit4.class)
+/**
+ * Build/Install/Run:
+ *  atest FrameworksServicesTests:MemoryStatUtilTest
+ */
 @SmallTest
 public class MemoryStatUtilTest {
     private static final String MEMORY_STAT_CONTENTS = String.join(
@@ -130,51 +131,51 @@
             "0");
 
     private static final String PROC_STATUS_CONTENTS = "Name:\tandroid.youtube\n"
-        + "State:\tS (sleeping)\n"
-        + "Tgid:\t12088\n"
-        + "Pid:\t12088\n"
-        + "PPid:\t723\n"
-        + "TracerPid:\t0\n"
-        + "Uid:\t10083\t10083\t10083\t10083\n"
-        + "Gid:\t10083\t10083\t10083\t10083\n"
-        + "Ngid:\t0\n"
-        + "FDSize:\t128\n"
-        + "Groups:\t3003 9997 20083 50083 \n"
-        + "VmPeak:\t 4546844 kB\n"
-        + "VmSize:\t 4542636 kB\n"
-        + "VmLck:\t       0 kB\n"
-        + "VmPin:\t       0 kB\n"
-        + "VmHWM:\t  137668 kB\n" // RSS high watermark
-        + "VmRSS:\t  126776 kB\n"
-        + "RssAnon:\t   37860 kB\n"
-        + "RssFile:\t   88764 kB\n"
-        + "RssShmem:\t     152 kB\n"
-        + "VmData:\t 4125112 kB\n"
-        + "VmStk:\t    8192 kB\n"
-        + "VmExe:\t      24 kB\n"
-        + "VmLib:\t  102432 kB\n"
-        + "VmPTE:\t    1300 kB\n"
-        + "VmPMD:\t      36 kB\n"
-        + "VmSwap:\t       0 kB\n"
-        + "Threads:\t95\n"
-        + "SigQ:\t0/13641\n"
-        + "SigPnd:\t0000000000000000\n"
-        + "ShdPnd:\t0000000000000000\n"
-        + "SigBlk:\t0000000000001204\n"
-        + "SigIgn:\t0000000000000001\n"
-        + "SigCgt:\t00000006400084f8\n"
-        + "CapInh:\t0000000000000000\n"
-        + "CapPrm:\t0000000000000000\n"
-        + "CapEff:\t0000000000000000\n"
-        + "CapBnd:\t0000000000000000\n"
-        + "CapAmb:\t0000000000000000\n"
-        + "Seccomp:\t2\n"
-        + "Cpus_allowed:\tff\n"
-        + "Cpus_allowed_list:\t0-7\n"
-        + "Mems_allowed:\t1\n"
-        + "Mems_allowed_list:\t0\n"
-        + "voluntary_ctxt_switches:\t903\n"
-        + "nonvoluntary_ctxt_switches:\t104\n";
+            + "State:\tS (sleeping)\n"
+            + "Tgid:\t12088\n"
+            + "Pid:\t12088\n"
+            + "PPid:\t723\n"
+            + "TracerPid:\t0\n"
+            + "Uid:\t10083\t10083\t10083\t10083\n"
+            + "Gid:\t10083\t10083\t10083\t10083\n"
+            + "Ngid:\t0\n"
+            + "FDSize:\t128\n"
+            + "Groups:\t3003 9997 20083 50083 \n"
+            + "VmPeak:\t 4546844 kB\n"
+            + "VmSize:\t 4542636 kB\n"
+            + "VmLck:\t       0 kB\n"
+            + "VmPin:\t       0 kB\n"
+            + "VmHWM:\t  137668 kB\n" // RSS high watermark
+            + "VmRSS:\t  126776 kB\n"
+            + "RssAnon:\t   37860 kB\n"
+            + "RssFile:\t   88764 kB\n"
+            + "RssShmem:\t     152 kB\n"
+            + "VmData:\t 4125112 kB\n"
+            + "VmStk:\t    8192 kB\n"
+            + "VmExe:\t      24 kB\n"
+            + "VmLib:\t  102432 kB\n"
+            + "VmPTE:\t    1300 kB\n"
+            + "VmPMD:\t      36 kB\n"
+            + "VmSwap:\t       0 kB\n"
+            + "Threads:\t95\n"
+            + "SigQ:\t0/13641\n"
+            + "SigPnd:\t0000000000000000\n"
+            + "ShdPnd:\t0000000000000000\n"
+            + "SigBlk:\t0000000000001204\n"
+            + "SigIgn:\t0000000000000001\n"
+            + "SigCgt:\t00000006400084f8\n"
+            + "CapInh:\t0000000000000000\n"
+            + "CapPrm:\t0000000000000000\n"
+            + "CapEff:\t0000000000000000\n"
+            + "CapBnd:\t0000000000000000\n"
+            + "CapAmb:\t0000000000000000\n"
+            + "Seccomp:\t2\n"
+            + "Cpus_allowed:\tff\n"
+            + "Cpus_allowed_list:\t0-7\n"
+            + "Mems_allowed:\t1\n"
+            + "Mems_allowed_list:\t0\n"
+            + "voluntary_ctxt_switches:\t903\n"
+            + "nonvoluntary_ctxt_switches:\t104\n";
 
     @Test
     public void testParseMemoryStatFromMemcg_parsesCorrectValues() {
diff --git a/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java b/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java
index 75e1d0d..bd03a8d 100644
--- a/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/am/UserControllerTest.java
@@ -11,7 +11,7 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
 package com.android.server.am;
@@ -19,6 +19,8 @@
 import static android.content.pm.PackageManager.PERMISSION_GRANTED;
 import static android.testing.DexmakerShareClassLoaderRule.runWithDexmakerShareClassLoader;
 
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
 import static com.android.server.am.UserController.CONTINUE_USER_SWITCH_MSG;
 import static com.android.server.am.UserController.REPORT_LOCKED_BOOT_COMPLETE_MSG;
 import static com.android.server.am.UserController.REPORT_USER_SWITCH_COMPLETE_MSG;
@@ -49,8 +51,6 @@
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
-import static androidx.test.InstrumentationRegistry.getTargetContext;
-
 import android.app.IUserSwitchObserver;
 import android.content.Context;
 import android.content.IIntentReceiver;
@@ -68,6 +68,9 @@
 import android.platform.test.annotations.Presubmit;
 import android.util.Log;
 
+import androidx.test.filters.FlakyTest;
+import androidx.test.filters.SmallTest;
+
 import com.android.server.pm.UserManagerService;
 import com.android.server.wm.WindowManagerService;
 
@@ -81,20 +84,18 @@
 import java.util.List;
 import java.util.Set;
 
-import androidx.test.filters.SmallTest;
-
 /**
  * Tests for {@link UserController}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:com.android.server.am.UserControllerTest
+ *  atest FrameworksServicesTests:UserControllerTest
  */
-@Presubmit
 @SmallTest
+@Presubmit
 public class UserControllerTest {
     private static final int TEST_USER_ID = 10;
     private static final int NONEXIST_USER_ID = 2;
-    private static String TAG = UserControllerTest.class.getSimpleName();
+    private static final String TAG = UserControllerTest.class.getSimpleName();
     private UserController mUserController;
     private TestInjector mInjector;
 
@@ -121,7 +122,7 @@
     @Before
     public void setUp() throws Exception {
         runWithDexmakerShareClassLoader(() -> {
-            mInjector = spy(new TestInjector(getTargetContext()));
+            mInjector = spy(new TestInjector(getInstrumentation().getTargetContext()));
             doNothing().when(mInjector).clearAllLockedTasks(anyString());
             doNothing().when(mInjector).startHomeActivity(anyInt(), anyString());
             doReturn(false).when(mInjector).stackSupervisorSwitchUser(anyInt(), any());
@@ -133,7 +134,7 @@
 
     @After
     public void tearDown() throws Exception {
-        mInjector.handlerThread.quit();
+        mInjector.mHandlerThread.quit();
         validateMockitoUsage();
     }
 
@@ -148,6 +149,7 @@
         startForegroundUserAssertions();
     }
 
+    @FlakyTest(bugId = 118932054)
     @Test
     public void testStartUser_background() {
         mUserController.startUser(TEST_USER_ID, false /* foreground */);
@@ -169,8 +171,8 @@
 
     private void startUserAssertions(
             List<String> expectedActions, Set<Integer> expectedMessageCodes) {
-        assertEquals(expectedActions, getActions(mInjector.sentIntents));
-        Set<Integer> actualCodes = mInjector.handler.getMessageCodes();
+        assertEquals(expectedActions, getActions(mInjector.mSentIntents));
+        Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes();
         assertEquals("Unexpected message sent", expectedMessageCodes, actualCodes);
     }
 
@@ -180,7 +182,7 @@
 
     private void startForegroundUserAssertions() {
         startUserAssertions(START_FOREGROUND_USER_ACTIONS, START_FOREGROUND_USER_MESSAGE_CODES);
-        Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG);
+        Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG);
         assertNotNull(reportMsg);
         UserState userState = (UserState) reportMsg.obj;
         assertNotNull(userState);
@@ -211,19 +213,19 @@
         mUserController.registerUserSwitchObserver(observer, "mock");
         // Start user -- this will update state of mUserController
         mUserController.startUser(TEST_USER_ID, true);
-        Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG);
+        Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG);
         assertNotNull(reportMsg);
         UserState userState = (UserState) reportMsg.obj;
         int oldUserId = reportMsg.arg1;
         int newUserId = reportMsg.arg2;
         // Call dispatchUserSwitch and verify that observer was called only once
-        mInjector.handler.clearAllRecordedMessages();
+        mInjector.mHandler.clearAllRecordedMessages();
         mUserController.dispatchUserSwitch(userState, oldUserId, newUserId);
         verify(observer, times(1)).onUserSwitching(eq(TEST_USER_ID), any());
         Set<Integer> expectedCodes = Collections.singleton(CONTINUE_USER_SWITCH_MSG);
-        Set<Integer> actualCodes = mInjector.handler.getMessageCodes();
+        Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes();
         assertEquals("Unexpected message sent", expectedCodes, actualCodes);
-        Message conMsg = mInjector.handler.getMessageForCode(CONTINUE_USER_SWITCH_MSG);
+        Message conMsg = mInjector.mHandler.getMessageForCode(CONTINUE_USER_SWITCH_MSG);
         assertNotNull(conMsg);
         userState = (UserState) conMsg.obj;
         assertNotNull(userState);
@@ -241,17 +243,17 @@
         mUserController.registerUserSwitchObserver(observer, "mock");
         // Start user -- this will update state of mUserController
         mUserController.startUser(TEST_USER_ID, true);
-        Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG);
+        Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG);
         assertNotNull(reportMsg);
         UserState userState = (UserState) reportMsg.obj;
         int oldUserId = reportMsg.arg1;
         int newUserId = reportMsg.arg2;
         // Call dispatchUserSwitch and verify that observer was called only once
-        mInjector.handler.clearAllRecordedMessages();
+        mInjector.mHandler.clearAllRecordedMessages();
         mUserController.dispatchUserSwitch(userState, oldUserId, newUserId);
         verify(observer, times(1)).onUserSwitching(eq(TEST_USER_ID), any());
         // Verify that CONTINUE_USER_SWITCH_MSG is not sent (triggers timeout)
-        Set<Integer> actualCodes = mInjector.handler.getMessageCodes();
+        Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes();
         assertWithMessage("No messages should be sent").that(actualCodes).isEmpty();
     }
 
@@ -259,12 +261,12 @@
     public void testContinueUserSwitch() {
         // Start user -- this will update state of mUserController
         mUserController.startUser(TEST_USER_ID, true);
-        Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG);
+        Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG);
         assertNotNull(reportMsg);
         UserState userState = (UserState) reportMsg.obj;
         int oldUserId = reportMsg.arg1;
         int newUserId = reportMsg.arg2;
-        mInjector.handler.clearAllRecordedMessages();
+        mInjector.mHandler.clearAllRecordedMessages();
         // Verify that continueUserSwitch worked as expected
         mUserController.continueUserSwitch(userState, oldUserId, newUserId);
         verify(mInjector.getWindowManager(), times(1)).stopFreezingScreen();
@@ -276,12 +278,12 @@
         mUserController.mUserSwitchUiEnabled = false;
         // Start user -- this will update state of mUserController
         mUserController.startUser(TEST_USER_ID, true);
-        Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG);
+        Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG);
         assertNotNull(reportMsg);
         UserState userState = (UserState) reportMsg.obj;
         int oldUserId = reportMsg.arg1;
         int newUserId = reportMsg.arg2;
-        mInjector.handler.clearAllRecordedMessages();
+        mInjector.mHandler.clearAllRecordedMessages();
         // Verify that continueUserSwitch worked as expected
         mUserController.continueUserSwitch(userState, oldUserId, newUserId);
         verify(mInjector.getWindowManager(), never()).stopFreezingScreen();
@@ -290,9 +292,9 @@
 
     private void continueUserSwitchAssertions() {
         Set<Integer> expectedCodes = Collections.singleton(REPORT_USER_SWITCH_COMPLETE_MSG);
-        Set<Integer> actualCodes = mInjector.handler.getMessageCodes();
+        Set<Integer> actualCodes = mInjector.mHandler.getMessageCodes();
         assertEquals("Unexpected message sent", expectedCodes, actualCodes);
-        Message msg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_COMPLETE_MSG);
+        Message msg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_COMPLETE_MSG);
         assertNotNull(msg);
         assertEquals("Unexpected userId", TEST_USER_ID, msg.arg1);
     }
@@ -305,10 +307,10 @@
         mUserController.registerUserSwitchObserver(observer, "mock");
         // Start user -- this will update state of mUserController
         mUserController.startUser(TEST_USER_ID, true);
-        Message reportMsg = mInjector.handler.getMessageForCode(REPORT_USER_SWITCH_MSG);
+        Message reportMsg = mInjector.mHandler.getMessageForCode(REPORT_USER_SWITCH_MSG);
         assertNotNull(reportMsg);
         int newUserId = reportMsg.arg2;
-        mInjector.handler.clearAllRecordedMessages();
+        mInjector.mHandler.clearAllRecordedMessages();
         // Mockito can't reset only interactions, so just verify that this hasn't been
         // called with 'false' until after dispatchUserSwitchComplete.
         verify(mInjector.getWindowManager(), never()).setSwitchingUser(false);
@@ -321,7 +323,7 @@
 
     private void setUpUser(int userId, int flags) {
         UserInfo userInfo = new UserInfo(userId, "User" + userId, flags);
-        when(mInjector.userManagerMock.getUserInfo(eq(userId))).thenReturn(userInfo);
+        when(mInjector.mUserManagerMock.getUserInfo(eq(userId))).thenReturn(userInfo);
     }
 
     private static List<String> getActions(List<Intent> intents) {
@@ -334,45 +336,46 @@
 
     // Should be public to allow mocking
     private static class TestInjector extends UserController.Injector {
-        TestHandler handler;
-        TestHandler uiHandler;
-        HandlerThread handlerThread;
-        UserManagerService userManagerMock;
-        UserManagerInternal userManagerInternalMock;
-        WindowManagerService windowManagerMock;
-        private Context mCtx;
-        List<Intent> sentIntents = new ArrayList<>();
+        public final TestHandler mHandler;
+        public final HandlerThread mHandlerThread;
+        public final UserManagerService mUserManagerMock;
+        public final List<Intent> mSentIntents = new ArrayList<>();
+
+        private final TestHandler mUiHandler;
+        private final UserManagerInternal mUserManagerInternalMock;
+        private final WindowManagerService mWindowManagerMock;
+        private final Context mCtx;
 
         TestInjector(Context ctx) {
             super(null);
             mCtx = ctx;
-            handlerThread = new HandlerThread(TAG);
-            handlerThread.start();
-            handler = new TestHandler(handlerThread.getLooper());
-            uiHandler = new TestHandler(handlerThread.getLooper());
-            userManagerMock = mock(UserManagerService.class);
-            userManagerInternalMock = mock(UserManagerInternal.class);
-            windowManagerMock = mock(WindowManagerService.class);
+            mHandlerThread = new HandlerThread(TAG);
+            mHandlerThread.start();
+            mHandler = new TestHandler(mHandlerThread.getLooper());
+            mUiHandler = new TestHandler(mHandlerThread.getLooper());
+            mUserManagerMock = mock(UserManagerService.class);
+            mUserManagerInternalMock = mock(UserManagerInternal.class);
+            mWindowManagerMock = mock(WindowManagerService.class);
         }
 
         @Override
         protected Handler getHandler(Handler.Callback callback) {
-            return handler;
+            return mHandler;
         }
 
         @Override
         protected Handler getUiHandler(Handler.Callback callback) {
-            return uiHandler;
+            return mUiHandler;
         }
 
         @Override
         protected UserManagerService getUserManager() {
-            return userManagerMock;
+            return mUserManagerMock;
         }
 
         @Override
         UserManagerInternal getUserManagerInternal() {
-            return userManagerInternalMock;
+            return mUserManagerInternalMock;
         }
 
         @Override
@@ -388,7 +391,7 @@
 
         @Override
         WindowManagerService getWindowManager() {
-            return windowManagerMock;
+            return mWindowManagerMock;
         }
 
         @Override
@@ -402,7 +405,7 @@
                 String[] requiredPermissions, int appOp, Bundle bOptions, boolean ordered,
                 boolean sticky, int callingPid, int callingUid, int userId) {
             Log.i(TAG, "broadcastIntentLocked " + intent);
-            sentIntents.add(intent);
+            mSentIntents.add(intent);
             return 0;
         }
 
diff --git a/services/tests/servicestests/src/com/android/server/net/watchlist/NetworkWatchlistServiceTests.java b/services/tests/servicestests/src/com/android/server/net/watchlist/NetworkWatchlistServiceTests.java
index b5a354c..9c8a382 100644
--- a/services/tests/servicestests/src/com/android/server/net/watchlist/NetworkWatchlistServiceTests.java
+++ b/services/tests/servicestests/src/com/android/server/net/watchlist/NetworkWatchlistServiceTests.java
@@ -51,7 +51,9 @@
 @MediumTest
 public class NetworkWatchlistServiceTests {
 
-    private static final long NETWOR_EVENT_TIMEOUT_SEC = 1;
+    private static final long NETWORK_EVENT_TIMEOUT_SEC = 1;
+    private static final int TEST_NETID = 100;
+    private static final int TEST_EVENT_TYPE = 1;
     private static final String TEST_HOST = "testhost.com";
     private static final String TEST_IP = "7.6.8.9";
     private static final String[] TEST_IPS =
@@ -180,8 +182,9 @@
                     }
                 };
         mWatchlistService.mNetworkWatchlistHandler = testDnsHandler;
-        connectivityMetrics.callback.onDnsEvent(TEST_HOST, TEST_IPS, TEST_IPS.length, 123L, 456);
-        if (!testDnsLatch.await(NETWOR_EVENT_TIMEOUT_SEC, TimeUnit.SECONDS)) {
+        connectivityMetrics.callback.onDnsEvent(TEST_NETID, TEST_EVENT_TYPE, 0,
+                TEST_HOST, TEST_IPS, TEST_IPS.length, 123L, 456);
+        if (!testDnsLatch.await(NETWORK_EVENT_TIMEOUT_SEC, TimeUnit.SECONDS)) {
             fail("Timed out waiting for network event");
         }
         assertEquals(TEST_HOST, dnsParams[0]);
@@ -206,7 +209,7 @@
                 };
         mWatchlistService.mNetworkWatchlistHandler = testConnectHandler;
         connectivityMetrics.callback.onConnectEvent(TEST_IP, 80, 123L, 456);
-        if (!testConnectLatch.await(NETWOR_EVENT_TIMEOUT_SEC, TimeUnit.SECONDS)) {
+        if (!testConnectLatch.await(NETWORK_EVENT_TIMEOUT_SEC, TimeUnit.SECONDS)) {
             fail("Timed out waiting for network event");
         }
         assertNull(connectParams[0]);
diff --git a/services/tests/servicestests/src/com/android/server/wm/AppTransitionControllerTest.java b/services/tests/servicestests/src/com/android/server/wm/AppTransitionControllerTest.java
index aa495f7..fc3ca93 100644
--- a/services/tests/servicestests/src/com/android/server/wm/AppTransitionControllerTest.java
+++ b/services/tests/servicestests/src/com/android/server/wm/AppTransitionControllerTest.java
@@ -48,7 +48,7 @@
 
     @Test
     public void testTranslucentOpen() throws Exception {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             final AppWindowToken behind = createAppWindowToken(mDisplayContent,
                     WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
             final AppWindowToken translucentOpening = createAppWindowToken(mDisplayContent,
@@ -65,7 +65,7 @@
 
     @Test
     public void testTranslucentClose() throws Exception {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             final AppWindowToken behind = createAppWindowToken(mDisplayContent,
                     WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD);
             final AppWindowToken translucentClosing = createAppWindowToken(mDisplayContent,
diff --git a/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java b/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
index cb8ca7e..8b75570 100644
--- a/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/DisplayContentTests.java
@@ -583,7 +583,7 @@
     }
 
     private void updateFocusedWindow() {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             sWm.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, false);
         }
     }
diff --git a/services/tests/servicestests/src/com/android/server/wm/DragDropControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/DragDropControllerTests.java
index 3c8b2a0..31b2fef 100644
--- a/services/tests/servicestests/src/com/android/server/wm/DragDropControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/DragDropControllerTests.java
@@ -121,7 +121,7 @@
         doReturn(mWindow).when(mDisplayContent).getTouchableWinAtPointLocked(0, 0);
         when(sWm.mInputManager.transferTouchFocus(any(), any())).thenReturn(true);
 
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             sWm.mWindowMap.put(mWindow.mClient.asBinder(), mWindow);
         }
     }
@@ -131,7 +131,7 @@
     public void tearDown() throws Exception {
         LocalServices.removeServiceForTest(UserManagerInternal.class);
         final CountDownLatch latch;
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             if (!mTarget.dragDropActiveLocked()) {
                 return;
             }
diff --git a/services/tests/servicestests/src/com/android/server/wm/RootWindowContainerTests.java b/services/tests/servicestests/src/com/android/server/wm/RootWindowContainerTests.java
index c1db6a6..001bed9 100644
--- a/services/tests/servicestests/src/com/android/server/wm/RootWindowContainerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/RootWindowContainerTests.java
@@ -24,7 +24,7 @@
 public class RootWindowContainerTests extends WindowTestsBase {
     @Test
     public void testSetDisplayOverrideConfigurationIfNeeded() throws Exception {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             // Add first stack we expect to be updated with configuration change.
             final TaskStack stack = createTaskStackOnDisplay(mDisplayContent);
             stack.getOverrideConfiguration().windowConfiguration.setBounds(new Rect(0, 0, 5, 5));
diff --git a/services/tests/servicestests/src/com/android/server/wm/TaskPositioningControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/TaskPositioningControllerTests.java
index f8e7403..d1480c5 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TaskPositioningControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TaskPositioningControllerTests.java
@@ -65,21 +65,21 @@
 
         mWindow = createWindow(null, TYPE_BASE_APPLICATION, "window");
         mWindow.mInputChannel = new InputChannel();
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             sWm.mWindowMap.put(mWindow.mClient.asBinder(), mWindow);
         }
     }
 
     @Test
     public void testStartAndFinishPositioning() throws Exception {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             assertFalse(mTarget.isPositioningLocked());
             assertNull(mTarget.getDragWindowHandleLocked());
         }
 
         assertTrue(mTarget.startMovingTask(mWindow.mClient, 0, 0));
 
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             assertTrue(mTarget.isPositioningLocked());
             assertNotNull(mTarget.getDragWindowHandleLocked());
         }
@@ -94,7 +94,7 @@
 
     @Test
     public void testHandleTapOutsideTask() throws Exception {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
 
             assertFalse(mTarget.isPositioningLocked());
             assertNull(mTarget.getDragWindowHandleLocked());
@@ -108,7 +108,7 @@
         // Wait until the looper processes finishTaskPositioning.
         assertTrue(sWm.mH.runWithScissors(() -> {}, TIMEOUT_MS));
 
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             assertTrue(mTarget.isPositioningLocked());
             assertNotNull(mTarget.getDragWindowHandleLocked());
         }
diff --git a/services/tests/servicestests/src/com/android/server/wm/TestWindowManagerPolicy.java b/services/tests/servicestests/src/com/android/server/wm/TestWindowManagerPolicy.java
index 5159551..19abd9e 100644
--- a/services/tests/servicestests/src/com/android/server/wm/TestWindowManagerPolicy.java
+++ b/services/tests/servicestests/src/com/android/server/wm/TestWindowManagerPolicy.java
@@ -150,7 +150,7 @@
         final com.android.server.wm.WindowState window;
         final AppWindowToken atoken;
         final WindowManagerService wm = mWmSupplier.get();
-        synchronized (wm.mWindowMap) {
+        synchronized (wm.mGlobalLock) {
             atoken = wm.mRoot.getAppWindowToken(appToken);
             IWindow iWindow = mock(IWindow.class);
             doReturn(mock(IBinder.class)).when(iWindow).asBinder();
@@ -164,7 +164,7 @@
             mRunnableWhenAddingSplashScreen = null;
         }
         return () -> {
-            synchronized (wm.mWindowMap) {
+            synchronized (wm.mGlobalLock) {
                 atoken.removeChild(window);
                 atoken.startingWindow = null;
             }
diff --git a/services/tests/servicestests/src/com/android/server/wm/WallpaperControllerTests.java b/services/tests/servicestests/src/com/android/server/wm/WallpaperControllerTests.java
index 882e789..e3280ca 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WallpaperControllerTests.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WallpaperControllerTests.java
@@ -32,7 +32,7 @@
     public void testWallpaperScreenshot() {
         WindowSurfaceController windowSurfaceController = mock(WindowSurfaceController.class);
 
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             // No wallpaper
             final DisplayContent dc = createNewDisplay();
             Bitmap wallpaperBitmap = sWm.mRoot.mWallpaperController.screenshotWallpaperLocked();
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java
index a1b1640..e155be4 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowTestUtils.java
@@ -40,6 +40,7 @@
 import static org.mockito.Mockito.anyFloat;
 import static org.mockito.Mockito.anyInt;
 import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
@@ -50,15 +51,13 @@
  * to WindowManager related test functionality.
  */
 public class WindowTestUtils {
-    public static int sNextTaskId = 0;
+    private static int sNextTaskId = 0;
 
-    /**
-     * Retrieves an instance of a mock {@link WindowManagerService}.
-     */
-    public static WindowManagerService getMockWindowManagerService() {
+    /** Retrieves an instance of a mock {@link WindowManagerService}. */
+    static WindowManagerService getMockWindowManagerService() {
         final WindowManagerService service = mock(WindowManagerService.class);
-        final WindowHashMap windowMap = new WindowHashMap();
-        when(service.getWindowManagerLock()).thenReturn(windowMap);
+        final WindowManagerGlobalLock lock = new WindowManagerGlobalLock();
+        doReturn(lock).when(service).getWindowManagerLock();
         return service;
     }
 
@@ -116,7 +115,7 @@
     /** Creates a {@link Task} and adds it to the specified {@link TaskStack}. */
     public static Task createTaskInStack(WindowManagerService service, TaskStack stack,
             int userId) {
-        synchronized (service.mWindowMap) {
+        synchronized (service.mGlobalLock) {
             final Task newTask = new Task(sNextTaskId++, stack, userId, service, 0, false,
                     new ActivityManager.TaskDescription(), null);
             stack.addTask(newTask, POSITION_TOP);
@@ -140,7 +139,7 @@
     }
 
     static TestAppWindowToken createTestAppWindowToken(DisplayContent dc) {
-        synchronized (dc.mService.mWindowMap) {
+        synchronized (dc.mService.mGlobalLock) {
             return new TestAppWindowToken(dc);
         }
     }
@@ -213,7 +212,7 @@
 
     static TestWindowToken createTestWindowToken(int type, DisplayContent dc,
             boolean persistOnEmpty) {
-        synchronized (dc.mService.mWindowMap) {
+        synchronized (dc.mService.mGlobalLock) {
             return new TestWindowToken(type, dc, persistOnEmpty);
         }
     }
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java
index dcfe556..73bb1c9 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java
+++ b/services/tests/servicestests/src/com/android/server/wm/WindowTestsBase.java
@@ -122,7 +122,7 @@
 
             // Set-up some common windows.
             mCommonWindows = new HashSet();
-            synchronized (sWm.mWindowMap) {
+            synchronized (sWm.mGlobalLock) {
                 mWallpaperWindow = createCommonWindow(null, TYPE_WALLPAPER, "wallpaperWindow");
                 mImeWindow = createCommonWindow(null, TYPE_INPUT_METHOD, "mImeWindow");
                 mDisplayContent.mInputMethodWindow = mImeWindow;
@@ -164,7 +164,7 @@
 
             final LinkedList<WindowState> nonCommonWindows = new LinkedList<>();
 
-            synchronized (sWm.mWindowMap) {
+            synchronized (sWm.mGlobalLock) {
                 sWm.mRoot.forAllWindows(w -> {
                     if (!mCommonWindows.contains(w)) {
                         nonCommonWindows.addLast(w);
@@ -198,7 +198,7 @@
     }
 
     private WindowState createCommonWindow(WindowState parent, int type, String name) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             final WindowState win = createWindow(parent, type, name);
             mCommonWindows.add(win);
             // Prevent common windows from been IMe targets
@@ -216,7 +216,7 @@
 
     private WindowToken createWindowToken(
             DisplayContent dc, int windowingMode, int activityType, int type) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             if (type < FIRST_APPLICATION_WINDOW || type > LAST_APPLICATION_WINDOW) {
                 return WindowTestUtils.createTestWindowToken(type, dc);
             }
@@ -241,7 +241,7 @@
     }
 
     WindowState createWindow(WindowState parent, int type, String name) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             return (parent == null)
                     ? createWindow(parent, type, mDisplayContent, name)
                     : createWindow(parent, type, parent.mToken, name);
@@ -250,14 +250,14 @@
 
     WindowState createWindowOnStack(WindowState parent, int windowingMode, int activityType,
             int type, DisplayContent dc, String name) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             final WindowToken token = createWindowToken(dc, windowingMode, activityType, type);
             return createWindow(parent, type, token, name);
         }
     }
 
     WindowState createAppWindow(Task task, int type, String name) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             final AppWindowToken token = WindowTestUtils.createTestAppWindowToken(mDisplayContent);
             task.addChild(token, 0);
             return createWindow(null, type, token, name);
@@ -265,7 +265,7 @@
     }
 
     WindowState createWindow(WindowState parent, int type, DisplayContent dc, String name) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             final WindowToken token = createWindowToken(
                     dc, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, type);
             return createWindow(parent, type, token, name);
@@ -274,7 +274,7 @@
 
     WindowState createWindow(WindowState parent, int type, DisplayContent dc, String name,
             boolean ownerCanAddInternalSystemWindow) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             final WindowToken token = createWindowToken(
                     dc, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, type);
             return createWindow(parent, type, token, name, 0 /* ownerId */,
@@ -283,7 +283,7 @@
     }
 
     WindowState createWindow(WindowState parent, int type, WindowToken token, String name) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             return createWindow(parent, type, token, name, 0 /* ownerId */,
                     false /* ownerCanAddInternalSystemWindow */);
         }
@@ -298,7 +298,7 @@
     static WindowState createWindow(WindowState parent, int type, WindowToken token,
             String name, int ownerId, boolean ownerCanAddInternalSystemWindow,
             WindowManagerService service, Session session, IWindow iWindow) {
-        synchronized (service.mWindowMap) {
+        synchronized (service.mGlobalLock) {
             final WindowManager.LayoutParams attrs = new WindowManager.LayoutParams(type);
             attrs.setTitle(name);
 
@@ -315,13 +315,13 @@
 
     /** Creates a {@link TaskStack} and adds it to the specified {@link DisplayContent}. */
     TaskStack createTaskStackOnDisplay(DisplayContent dc) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             return createStackControllerOnDisplay(dc).mContainer;
         }
     }
 
     StackWindowController createStackControllerOnDisplay(DisplayContent dc) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             return createStackControllerOnStackOnDisplay(
                     WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, dc);
         }
@@ -329,7 +329,7 @@
 
     StackWindowController createStackControllerOnStackOnDisplay(
             int windowingMode, int activityType, DisplayContent dc) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             final Configuration overrideConfig = new Configuration();
             overrideConfig.windowConfiguration.setWindowingMode(windowingMode);
             overrideConfig.windowConfiguration.setActivityType(activityType);
@@ -351,7 +351,7 @@
         final int displayId = sNextDisplayId++;
         final Display display = new Display(DisplayManagerGlobal.getInstance(), displayId,
                 mDisplayInfo, DEFAULT_DISPLAY_ADJUSTMENTS);
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             return new DisplayContent(display, sWm, mWallpaperController,
                     mock(DisplayWindowController.class));
         }
@@ -376,7 +376,7 @@
         final Display display = new Display(DisplayManagerGlobal.getInstance(), displayId,
                 displayInfo, DEFAULT_DISPLAY_ADJUSTMENTS);
         final DisplayWindowController dcw = new DisplayWindowController(display, sWm);
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             // Display creation is driven by DisplayWindowController via ActivityStackSupervisor.
             // We skip those steps here.
             return sWm.mRoot.createDisplayContent(display, dcw);
@@ -386,7 +386,7 @@
     /** Creates a {@link com.android.server.wm.WindowTestUtils.TestWindowState} */
     WindowTestUtils.TestWindowState createWindowState(WindowManager.LayoutParams attrs,
             WindowToken token) {
-        synchronized (sWm.mWindowMap) {
+        synchronized (sWm.mGlobalLock) {
             return new WindowTestUtils.TestWindowState(sWm, mMockSession, mIWindow, attrs, token);
         }
     }
diff --git a/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java b/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java
index 1222b59..69db384 100644
--- a/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java
+++ b/services/tests/servicestests/utils/com/android/server/testutils/TestHandler.java
@@ -152,7 +152,7 @@
 
         @Override
         public int compareTo(MsgInfo o) {
-            return (int) (sendTime - o.sendTime);
+            return Long.compare(sendTime, o.sendTime);
         }
 
         @Override
diff --git a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
index b19cc86..38d8e39 100644
--- a/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
+++ b/services/tests/uiservicestests/src/com/android/server/notification/ZenModeHelperTest.java
@@ -21,13 +21,14 @@
 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_LIGHTS;
 import static android.app.NotificationManager.Policy.SUPPRESSED_EFFECT_PEEK;
 
-import static junit.framework.Assert.assertFalse;
 import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertFalse;
 import static junit.framework.TestCase.assertTrue;
 
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.atLeastOnce;
 import static org.mockito.Mockito.doNothing;
@@ -45,13 +46,14 @@
 import android.content.ComponentName;
 import android.content.ContentResolver;
 import android.content.Context;
+import android.content.pm.PackageManager;
 import android.content.res.Resources;
 import android.content.res.XmlResourceParser;
 import android.media.AudioAttributes;
 import android.media.AudioManager;
 import android.media.AudioManagerInternal;
-import android.media.VolumePolicy;
 import android.media.AudioSystem;
+import android.media.VolumePolicy;
 import android.net.Uri;
 import android.provider.Settings;
 import android.provider.Settings.Global;
@@ -67,9 +69,9 @@
 
 import com.android.internal.R;
 import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
-import com.android.server.notification.ManagedServices.UserProfiles;
 import com.android.internal.util.FastXmlSerializer;
 import com.android.server.UiServiceTestCase;
+import com.android.server.notification.ManagedServices.UserProfiles;
 
 import org.junit.Before;
 import org.junit.Test;
@@ -87,12 +89,16 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.Reader;
+import java.util.Objects;
 
 @SmallTest
 @RunWith(AndroidTestingRunner.class)
 @TestableLooper.RunWithLooper
 public class ZenModeHelperTest extends UiServiceTestCase {
 
+    private static final String EVENTS_DEFAULT_RULE_ID = "EVENTS_DEFAULT_RULE";
+    private static final String SCHEDULE_DEFAULT_RULE_ID = "EVERY_NIGHT_DEFAULT_RULE";
+
     ConditionProviders mConditionProviders;
     @Mock NotificationManager mNotificationManager;
     private Resources mResources;
@@ -108,7 +114,6 @@
         mTestableLooper = TestableLooper.get(this);
         mContext = spy(getContext());
         mContentResolver = mContext.getContentResolver();
-
         mResources = spy(mContext.getResources());
         try {
             when(mResources.getXml(R.xml.default_zen_mode_config)).thenReturn(
@@ -132,12 +137,13 @@
                 + "reminders=\"false\" events=\"false\" callsFrom=\"1\" messagesFrom=\"2\" "
                 + "visualScreenOff=\"true\" alarms=\"true\" "
                 + "media=\"true\" system=\"false\" />\n"
-                + "<automatic ruleId=\"EVENTS_DEFAULT_RULE\" enabled=\"false\" snoozing=\"false\""
+                + "<automatic ruleId=\"" + EVENTS_DEFAULT_RULE_ID
+                + "\" enabled=\"false\" snoozing=\"false\""
                 + " name=\"Event\" zen=\"1\""
                 + " component=\"android/com.android.server.notification.EventConditionProvider\""
                 + " conditionId=\"condition://android/event?userId=-10000&amp;calendar=&amp;"
                 + "reply=1\"/>\n"
-                + "<automatic ruleId=\"EVERY_NIGHT_DEFAULT_RULE\" enabled=\"false\""
+                + "<automatic ruleId=\"" + SCHEDULE_DEFAULT_RULE_ID + "\" enabled=\"false\""
                 + " snoozing=\"false\" name=\"Sleeping\" zen=\"1\""
                 + " component=\"android/com.android.server.notification.ScheduleConditionProvider\""
                 + " conditionId=\"condition://android/schedule?days=1.2.3.4.5.6.7 &amp;start=22.0"
@@ -770,8 +776,8 @@
         mZenModeHelperSpy.readXml(parser, false);
 
         assertEquals(SUPPRESSED_EFFECT_FULL_SCREEN_INTENT
-                | SUPPRESSED_EFFECT_LIGHTS
-                | SUPPRESSED_EFFECT_PEEK,
+                        | SUPPRESSED_EFFECT_LIGHTS
+                        | SUPPRESSED_EFFECT_PEEK,
                 mZenModeHelperSpy.mConfig.suppressedVisualEffects);
 
         xml = "<zen version=\"6\" user=\"0\">\n"
@@ -1007,6 +1013,90 @@
         mZenModeHelperSpy.updateDefaultZenRules(); // shouldn't throw null pointer
     }
 
+    @Test
+    public void testDoNotUpdateModifiedDefaultAutoRule() {
+        // mDefaultConfig is set to default config in setup by getDefaultConfigParser
+        when(mContext.checkCallingPermission(anyString()))
+                .thenReturn(PackageManager.PERMISSION_GRANTED);
+
+        // shouldn't update rule that's been modified
+        ZenModeConfig.ZenRule updatedDefaultRule = new ZenModeConfig.ZenRule();
+        updatedDefaultRule.modified = true;
+        updatedDefaultRule.enabled = false;
+        updatedDefaultRule.creationTime = 0;
+        updatedDefaultRule.id = SCHEDULE_DEFAULT_RULE_ID;
+        updatedDefaultRule.name = "Schedule Default Rule";
+        updatedDefaultRule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
+        updatedDefaultRule.conditionId = ZenModeConfig.toScheduleConditionId(new ScheduleInfo());
+        updatedDefaultRule.component = new ComponentName("android", "ScheduleConditionProvider");
+
+        ArrayMap<String, ZenModeConfig.ZenRule> autoRules = new ArrayMap<>();
+        autoRules.put(SCHEDULE_DEFAULT_RULE_ID, updatedDefaultRule);
+        mZenModeHelperSpy.mConfig.automaticRules = autoRules;
+
+        mZenModeHelperSpy.updateDefaultZenRules();
+        assertEquals(updatedDefaultRule,
+                mZenModeHelperSpy.mConfig.automaticRules.get(SCHEDULE_DEFAULT_RULE_ID));
+    }
+
+    @Test
+    public void testDoNotUpdateEnabledDefaultAutoRule() {
+        // mDefaultConfig is set to default config in setup by getDefaultConfigParser
+        when(mContext.checkCallingPermission(anyString()))
+                .thenReturn(PackageManager.PERMISSION_GRANTED);
+
+        // shouldn't update the rule that's enabled
+        ZenModeConfig.ZenRule updatedDefaultRule = new ZenModeConfig.ZenRule();
+        updatedDefaultRule.enabled = true;
+        updatedDefaultRule.modified = false;
+        updatedDefaultRule.creationTime = 0;
+        updatedDefaultRule.id = SCHEDULE_DEFAULT_RULE_ID;
+        updatedDefaultRule.name = "Schedule Default Rule";
+        updatedDefaultRule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
+        updatedDefaultRule.conditionId = ZenModeConfig.toScheduleConditionId(new ScheduleInfo());
+        updatedDefaultRule.component = new ComponentName("android", "ScheduleConditionProvider");
+
+        ArrayMap<String, ZenModeConfig.ZenRule> autoRules = new ArrayMap<>();
+        autoRules.put(SCHEDULE_DEFAULT_RULE_ID, updatedDefaultRule);
+        mZenModeHelperSpy.mConfig.automaticRules = autoRules;
+
+        mZenModeHelperSpy.updateDefaultZenRules();
+        assertEquals(updatedDefaultRule,
+                mZenModeHelperSpy.mConfig.automaticRules.get(SCHEDULE_DEFAULT_RULE_ID));
+    }
+
+    @Test
+    public void testUpdateDefaultAutoRule() {
+        // mDefaultConfig is set to default config in setup by getDefaultConfigParser
+        final String defaultRuleName = "rule name test";
+        when(mContext.checkCallingPermission(anyString()))
+                .thenReturn(PackageManager.PERMISSION_GRANTED);
+
+        // will update rule that is not enabled and modified
+        ZenModeConfig.ZenRule customDefaultRule = new ZenModeConfig.ZenRule();
+        customDefaultRule.enabled = false;
+        customDefaultRule.modified = false;
+        customDefaultRule.creationTime = 0;
+        customDefaultRule.id = SCHEDULE_DEFAULT_RULE_ID;
+        customDefaultRule.name = "Schedule Default Rule";
+        customDefaultRule.zenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
+        customDefaultRule.conditionId = ZenModeConfig.toScheduleConditionId(new ScheduleInfo());
+        customDefaultRule.component = new ComponentName("android", "ScheduleConditionProvider");
+
+        ArrayMap<String, ZenModeConfig.ZenRule> autoRules = new ArrayMap<>();
+        autoRules.put(SCHEDULE_DEFAULT_RULE_ID, customDefaultRule);
+        mZenModeHelperSpy.mConfig.automaticRules = autoRules;
+
+        mZenModeHelperSpy.updateDefaultZenRules();
+        ZenModeConfig.ZenRule ruleAfterUpdating =
+                mZenModeHelperSpy.mConfig.automaticRules.get(SCHEDULE_DEFAULT_RULE_ID);
+        assertEquals(customDefaultRule.enabled, ruleAfterUpdating.enabled);
+        assertEquals(customDefaultRule.modified, ruleAfterUpdating.modified);
+        assertEquals(customDefaultRule.id, ruleAfterUpdating.id);
+        assertEquals(customDefaultRule.conditionId, ruleAfterUpdating.conditionId);
+        assertFalse(Objects.equals(defaultRuleName, ruleAfterUpdating.name)); // update name
+    }
+
     private void setupZenConfig() {
         mZenModeHelperSpy.mZenMode = Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;
         mZenModeHelperSpy.mConfig.allowAlarms = false;
diff --git a/services/tests/wmtests/Android.mk b/services/tests/wmtests/Android.mk
index c095ae0..dd656c3 100644
--- a/services/tests/wmtests/Android.mk
+++ b/services/tests/wmtests/Android.mk
@@ -11,12 +11,18 @@
 # Include all test java files.
 LOCAL_SRC_FILES := \
     $(call all-java-files-under, src) \
-    $(call all-java-files-under, ../servicestests/utils)
+    $(call all-java-files-under, ../servicestests/utils) \
 
 LOCAL_STATIC_JAVA_LIBRARIES := \
+    frameworks-base-testutils \
+    services.core \
     androidx.test.runner \
+    androidx.test.rules \
     mockito-target-minus-junit4 \
     platform-test-annotations \
+    truth-prebuilt \
+    testables \
+    ub-uiautomator \
 
 LOCAL_JAVA_LIBRARIES := \
     android.test.mock \
diff --git a/services/tests/wmtests/AndroidManifest.xml b/services/tests/wmtests/AndroidManifest.xml
index 1fb9473..73a34b6 100644
--- a/services/tests/wmtests/AndroidManifest.xml
+++ b/services/tests/wmtests/AndroidManifest.xml
@@ -22,7 +22,27 @@
         android:minSdkVersion="1"
         android:targetSdkVersion="28" />
 
-    <application android:testOnly="true" />
+    <uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
+    <uses-permission android:name="android.permission.MANAGE_ACTIVITY_STACKS" />
+    <uses-permission android:name="android.permission.GET_TOP_ACTIVITY_INFO" />
+    <uses-permission android:name="android.permission.MANAGE_USERS" />
+    <uses-permission android:name="android.permission.STORAGE_INTERNAL" />
+    <uses-permission android:name="android.permission.ACCESS_KEYGUARD_SECURE_STORAGE" />
+    <uses-permission android:name="android.permission.STATUS_BAR_SERVICE" />
+    <uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
+    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
+    <uses-permission android:name="android.permission.ACCESS_SURFACE_FLINGER" />
+    <uses-permission android:name="android.permission.READ_FRAME_BUFFER" />
+
+    <application android:testOnly="true">
+        <activity android:name="com.android.server.wm.TaskStackChangedListenerTest$ActivityA" />
+        <activity android:name="com.android.server.wm.TaskStackChangedListenerTest$ActivityB" />
+        <activity android:name="com.android.server.wm.TaskStackChangedListenerTest$ActivityRequestedOrientationChange" />
+        <activity android:name="com.android.server.wm.TaskStackChangedListenerTest$ActivityTaskChangeCallbacks" />
+        <activity android:name="com.android.server.wm.TaskStackChangedListenerTest$ActivityTaskDescriptionChange" />
+        <activity android:name="com.android.server.wm.ScreenDecorWindowTests$TestActivity" />
+    </application>
 
     <instrumentation
         android:name="androidx.test.runner.AndroidJUnitRunner"
diff --git a/services/tests/wmtests/src/com/android/server/am/DummyAmTests.java b/services/tests/wmtests/src/com/android/server/am/DummyAmTests.java
deleted file mode 100644
index 023e4ab..0000000
--- a/services/tests/wmtests/src/com/android/server/am/DummyAmTests.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.am;
-
-import android.platform.test.annotations.Presubmit;
-
-import org.junit.Test;
-
-import androidx.test.filters.FlakyTest;
-
-/**
- * Dummy test for com.android.server.am.
- * TODO(b/113800711): Remove this class once the actual tests are moved from servicestests.
- */
-public class DummyAmTests {
-
-    @Presubmit
-    @Test
-    public void preSubmitTest() {}
-
-    @FlakyTest
-    @Presubmit
-    @Test
-    public void flakyPreSubmitTest() {}
-
-    @Test
-    public void postSubmitTest() {}
-
-    @FlakyTest
-    @Test
-    public void flakyPostSubmitTest() {}
-}
diff --git a/services/tests/wmtests/src/com/android/server/policy/DummyPolicyTests.java b/services/tests/wmtests/src/com/android/server/policy/DummyPolicyTests.java
deleted file mode 100644
index 03fb123..0000000
--- a/services/tests/wmtests/src/com/android/server/policy/DummyPolicyTests.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.policy;
-
-import android.platform.test.annotations.Presubmit;
-
-import org.junit.Test;
-
-import androidx.test.filters.FlakyTest;
-
-/**
- * Dummy test for com.android.server.policy.
- * TODO(b/113800711): Remove this class once the actual tests are moved from servicestests.
- */
-public class DummyPolicyTests {
-
-    @Presubmit
-    @Test
-    public void preSubmitTest() {}
-
-    @FlakyTest
-    @Presubmit
-    @Test
-    public void flakyPreSubmitTest() {}
-
-    @Test
-    public void postSubmitTest() {}
-
-    @FlakyTest
-    @Test
-    public void flakyPostSubmitTest() {}
-}
diff --git a/services/tests/servicestests/src/com/android/server/policy/FakeWindowState.java b/services/tests/wmtests/src/com/android/server/policy/FakeWindowState.java
similarity index 96%
rename from services/tests/servicestests/src/com/android/server/policy/FakeWindowState.java
rename to services/tests/wmtests/src/com/android/server/policy/FakeWindowState.java
index d34f951..d4f2b06 100644
--- a/services/tests/servicestests/src/com/android/server/policy/FakeWindowState.java
+++ b/services/tests/wmtests/src/com/android/server/policy/FakeWindowState.java
@@ -16,17 +16,13 @@
 
 package com.android.server.policy;
 
-import android.annotation.Nullable;
-import android.graphics.Point;
 import android.graphics.Rect;
 import android.util.proto.ProtoOutputStream;
 import android.view.Display;
-import android.view.DisplayCutout;
 import android.view.IApplicationToken;
 import android.view.WindowManager;
 
 import com.android.server.wm.WindowFrames;
-import com.android.server.wm.utils.WmDisplayCutout;
 
 public class FakeWindowState implements WindowManagerPolicy.WindowState {
 
@@ -243,10 +239,12 @@
     }
 
     @Override
-    public boolean canReceiveKeys() { return false; }
+    public boolean canReceiveKeys() {
+        return false;
+    }
 
     @Override
-    public void writeIdentifierToProto(ProtoOutputStream proto, long fieldId){
+    public void writeIdentifierToProto(ProtoOutputStream proto, long fieldId) {
         throw new UnsupportedOperationException("not implemented");
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerInsetsTest.java b/services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerInsetsTest.java
similarity index 92%
rename from services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerInsetsTest.java
rename to services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerInsetsTest.java
index cce6ba7..f024fe7 100644
--- a/services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerInsetsTest.java
+++ b/services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerInsetsTest.java
@@ -29,15 +29,16 @@
 import android.view.DisplayInfo;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Rule;
 import org.junit.Test;
 import org.junit.rules.ErrorCollector;
-import org.junit.runner.RunWith;
 
-@RunWith(AndroidJUnit4.class)
+/**
+ * Build/Install/Run:
+ *  atest WmTests:PhoneWindowManagerInsetsTest
+ */
 @SmallTest
 @Presubmit
 public class PhoneWindowManagerInsetsTest extends PhoneWindowManagerTestBase {
@@ -52,7 +53,7 @@
     }
 
     @Test
-    public void portrait() throws Exception {
+    public void portrait() {
         DisplayInfo di = displayInfoForRotation(ROTATION_0, false /* withCutout */);
 
         verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT);
@@ -61,7 +62,7 @@
     }
 
     @Test
-    public void portrait_withCutout() throws Exception {
+    public void portrait_withCutout() {
         DisplayInfo di = displayInfoForRotation(ROTATION_0, true /* withCutout */);
 
         verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT);
@@ -70,7 +71,7 @@
     }
 
     @Test
-    public void landscape() throws Exception {
+    public void landscape() {
         DisplayInfo di = displayInfoForRotation(ROTATION_90, false /* withCutout */);
 
         verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
@@ -79,7 +80,7 @@
     }
 
     @Test
-    public void landscape_withCutout() throws Exception {
+    public void landscape_withCutout() {
         DisplayInfo di = displayInfoForRotation(ROTATION_90, true /* withCutout */);
 
         verifyStableInsets(di, DISPLAY_CUTOUT_HEIGHT, STATUS_BAR_HEIGHT, NAV_BAR_HEIGHT, 0);
@@ -88,7 +89,7 @@
     }
 
     @Test
-    public void seascape() throws Exception {
+    public void seascape() {
         DisplayInfo di = displayInfoForRotation(ROTATION_270, false /* withCutout */);
 
         verifyStableInsets(di, NAV_BAR_HEIGHT, STATUS_BAR_HEIGHT, 0, 0);
@@ -97,7 +98,7 @@
     }
 
     @Test
-    public void seascape_withCutout() throws Exception {
+    public void seascape_withCutout() {
         DisplayInfo di = displayInfoForRotation(ROTATION_270, true /* withCutout */);
 
         verifyStableInsets(di, NAV_BAR_HEIGHT, STATUS_BAR_HEIGHT, DISPLAY_CUTOUT_HEIGHT, 0);
@@ -106,7 +107,7 @@
     }
 
     @Test
-    public void upsideDown() throws Exception {
+    public void upsideDown() {
         DisplayInfo di = displayInfoForRotation(ROTATION_180, false /* withCutout */);
 
         verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT);
@@ -115,7 +116,7 @@
     }
 
     @Test
-    public void upsideDown_withCutout() throws Exception {
+    public void upsideDown_withCutout() {
         DisplayInfo di = displayInfoForRotation(ROTATION_180, true /* withCutout */);
 
         verifyStableInsets(di, 0, STATUS_BAR_HEIGHT, 0, NAV_BAR_HEIGHT + DISPLAY_CUTOUT_HEIGHT);
@@ -181,4 +182,4 @@
         return mPolicy.getConfigDisplayHeight(di.logicalWidth, di.logicalHeight, di.rotation,
                 0 /* ui */, Display.DEFAULT_DISPLAY, di.displayCutout);
     }
-}
\ No newline at end of file
+}
diff --git a/services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerLayoutTest.java b/services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerLayoutTest.java
similarity index 97%
rename from services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerLayoutTest.java
rename to services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerLayoutTest.java
index fee761d..e8f767a 100644
--- a/services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerLayoutTest.java
+++ b/services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerLayoutTest.java
@@ -43,13 +43,14 @@
 import android.view.WindowManager;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
-@RunWith(AndroidJUnit4.class)
+/**
+ * Build/Install/Run:
+ *  atest WmTests:PhoneWindowManagerLayoutTest
+ */
 @SmallTest
 @Presubmit
 public class PhoneWindowManagerLayoutTest extends PhoneWindowManagerTestBase {
@@ -69,7 +70,7 @@
     }
 
     @Test
-    public void layoutWindowLw_appDrawsBars() throws Exception {
+    public void layoutWindowLw_appDrawsBars() {
         mAppWindow.attrs.flags |= FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
         mPolicy.addWindow(mAppWindow);
 
@@ -84,7 +85,7 @@
     }
 
     @Test
-    public void layoutWindowLw_appWontDrawBars() throws Exception {
+    public void layoutWindowLw_appWontDrawBars() {
         mAppWindow.attrs.flags &= ~FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
         mPolicy.addWindow(mAppWindow);
 
@@ -99,7 +100,7 @@
     }
 
     @Test
-    public void layoutWindowLw_appWontDrawBars_forceStatus() throws Exception {
+    public void layoutWindowLw_appWontDrawBars_forceStatus() {
         mAppWindow.attrs.flags &= ~FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS;
         mAppWindow.attrs.privateFlags |= PRIVATE_FLAG_FORCE_DRAW_STATUS_BAR_BACKGROUND;
         mPolicy.addWindow(mAppWindow);
@@ -391,4 +392,4 @@
         assertThat(outOutsets, is(new Rect()));
         assertThat(outDisplayCutout, is(new DisplayCutout.ParcelableWrapper()));
     }
-}
\ No newline at end of file
+}
diff --git a/services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerTest.java b/services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerTest.java
similarity index 95%
rename from services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerTest.java
rename to services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerTest.java
index d92d7e0..6c44d65 100644
--- a/services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerTest.java
+++ b/services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerTest.java
@@ -47,12 +47,13 @@
 import android.view.WindowManager;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
-@RunWith(AndroidJUnit4.class)
+/**
+ * Build/Install/Run:
+ *  atest WmTests:PhoneWindowManagerTest
+ */
 @SmallTest
 @Presubmit
 public class PhoneWindowManagerTest {
@@ -95,7 +96,7 @@
 
 
     @Test
-    public void testChooseNavigationColorWindowLw() throws Exception {
+    public void testChooseNavigationColorWindowLw() {
         final FakeWindowState opaque = createOpaqueFullscreen(false);
 
         final FakeWindowState dimmingImTarget = createDimmingDialogWindow(true);
@@ -147,14 +148,14 @@
     }
 
     @Test
-    public void testUpdateLightNavigationBarLw() throws Exception {
+    public void testUpdateLightNavigationBarLw() {
         final FakeWindowState opaqueDarkNavBar = createOpaqueFullscreen(false);
         final FakeWindowState opaqueLightNavBar = createOpaqueFullscreen(true);
 
         final FakeWindowState dimming = createDimmingDialogWindow(false);
 
-        final FakeWindowState imeDrawDarkNavBar = createInputMethodWindow(true,true, false);
-        final FakeWindowState imeDrawLightNavBar = createInputMethodWindow(true,true, true);
+        final FakeWindowState imeDrawDarkNavBar = createInputMethodWindow(true, true, false);
+        final FakeWindowState imeDrawLightNavBar = createInputMethodWindow(true, true, true);
 
         assertEquals(SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR,
                 PhoneWindowManager.updateLightNavigationBarLw(
@@ -204,7 +205,7 @@
     }
 
     @Test
-    public void testIsDockSideAllowedDockTop() throws Exception {
+    public void testIsDockSideAllowedDockTop() {
         // Docked top is always allowed
         assertTrue(PhoneWindowManager.isDockSideAllowed(DOCKED_TOP, DOCKED_LEFT, NAV_BAR_BOTTOM,
                 true /* navigationBarCanMove */));
@@ -213,14 +214,14 @@
     }
 
     @Test
-    public void testIsDockSideAllowedDockBottom() throws Exception {
+    public void testIsDockSideAllowedDockBottom() {
         // Cannot dock bottom
         assertFalse(PhoneWindowManager.isDockSideAllowed(DOCKED_BOTTOM, DOCKED_LEFT, NAV_BAR_BOTTOM,
                 true /* navigationBarCanMove */));
     }
 
     @Test
-    public void testIsDockSideAllowedNavigationBarMovable() throws Exception {
+    public void testIsDockSideAllowedNavigationBarMovable() {
         assertFalse(PhoneWindowManager.isDockSideAllowed(DOCKED_LEFT, DOCKED_LEFT, NAV_BAR_BOTTOM,
                 true /* navigationBarCanMove */));
         assertFalse(PhoneWindowManager.isDockSideAllowed(DOCKED_LEFT, DOCKED_LEFT, NAV_BAR_LEFT,
@@ -236,7 +237,7 @@
     }
 
     @Test
-    public void testIsDockSideAllowedNavigationBarNotMovable() throws Exception {
+    public void testIsDockSideAllowedNavigationBarNotMovable() {
         // Navigation bar is not movable such as tablets
         assertTrue(PhoneWindowManager.isDockSideAllowed(DOCKED_LEFT, DOCKED_LEFT, NAV_BAR_BOTTOM,
                 false /* navigationBarCanMove */));
diff --git a/services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerTestBase.java b/services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerTestBase.java
similarity index 97%
rename from services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerTestBase.java
rename to services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerTestBase.java
index e16f118..fc8fe23 100644
--- a/services/tests/servicestests/src/com/android/server/policy/PhoneWindowManagerTestBase.java
+++ b/services/tests/wmtests/src/com/android/server/policy/PhoneWindowManagerTestBase.java
@@ -64,7 +64,7 @@
 
 import org.junit.Before;
 
-public class PhoneWindowManagerTestBase {
+class PhoneWindowManagerTestBase {
     static final int DISPLAY_WIDTH = 500;
     static final int DISPLAY_HEIGHT = 1000;
 
@@ -82,7 +82,7 @@
     private int mRotation = ROTATION_0;
 
     @Before
-    public void setUpBase() throws Exception {
+    public void setUpBase() {
         mContext = new TestContextWrapper(InstrumentationRegistry.getTargetContext());
         mContext.getResourceMocker().addOverride(
                 com.android.internal.R.dimen.status_bar_height_portrait, STATUS_BAR_HEIGHT);
@@ -207,7 +207,7 @@
     static class TestContextWrapper extends ContextWrapper {
         private final TestableResources mResourceMocker;
 
-        public TestContextWrapper(Context targetContext) {
+        TestContextWrapper(Context targetContext) {
             super(targetContext);
             mResourceMocker = new TestableResources(targetContext.getResources());
         }
@@ -234,7 +234,7 @@
 
     static class TestablePhoneWindowManager extends PhoneWindowManager {
 
-        public TestablePhoneWindowManager() {
+        TestablePhoneWindowManager() {
         }
 
         @Override
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityDisplayTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java
similarity index 96%
rename from services/tests/servicestests/src/com/android/server/am/ActivityDisplayTests.java
rename to services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java
index 59c4067..d3f1a0a 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityDisplayTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityDisplayTests.java
@@ -11,10 +11,10 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
@@ -22,7 +22,7 @@
 import static android.content.pm.ActivityInfo.FLAG_ALWAYS_FOCUSABLE;
 import static android.content.pm.ActivityInfo.FLAG_SHOW_WHEN_LOCKED;
 
-import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
+import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNull;
@@ -32,11 +32,9 @@
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link ActivityDisplay} class.
@@ -46,13 +44,10 @@
  */
 @SmallTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class ActivityDisplayTests extends ActivityTestsBase {
 
     @Before
-    @Override
     public void setUp() throws Exception {
-        super.setUp();
         setupActivityTaskManagerService();
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityOptionsTest.java b/services/tests/wmtests/src/com/android/server/wm/ActivityOptionsTest.java
similarity index 85%
rename from services/tests/servicestests/src/com/android/server/am/ActivityOptionsTest.java
rename to services/tests/wmtests/src/com/android/server/wm/ActivityOptionsTest.java
index d15bff4..c449049 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityOptionsTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityOptionsTest.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
@@ -22,23 +22,22 @@
 import static android.view.WindowManager.LayoutParams.ROTATION_ANIMATION_ROTATE;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
 
 import android.app.ActivityOptions;
 import android.os.Bundle;
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 /**
- * atest FrameworksServicesTests:ActivityOptionsTest
+ * Build/Install/Run:
+ *  atest WmTests:ActivityOptionsTest
  */
 @MediumTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class ActivityOptionsTest {
 
     @Test
@@ -64,12 +63,12 @@
         assertEquals(Integer.MAX_VALUE, restoredOpts.getLaunchDisplayId());
         assertEquals(ACTIVITY_TYPE_STANDARD, restoredOpts.getLaunchActivityType());
         assertEquals(WINDOWING_MODE_FULLSCREEN, restoredOpts.getLaunchWindowingMode());
-        assertEquals(true, restoredOpts.getAvoidMoveToFront());
+        assertTrue(restoredOpts.getAvoidMoveToFront());
         assertEquals(Integer.MAX_VALUE, restoredOpts.getLaunchTaskId());
-        assertEquals(true, restoredOpts.getLockTaskMode());
+        assertTrue(restoredOpts.getLockTaskMode());
         assertEquals(ROTATION_ANIMATION_ROTATE, restoredOpts.getRotationAnimationHint());
-        assertEquals(true, restoredOpts.getTaskOverlay());
-        assertEquals(true, restoredOpts.canTaskOverlayResume());
+        assertTrue(restoredOpts.getTaskOverlay());
+        assertTrue(restoredOpts.canTaskOverlayResume());
         assertEquals(SPLIT_SCREEN_CREATE_MODE_BOTTOM_OR_RIGHT,
                 restoredOpts.getSplitScreenCreateMode());
     }
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
similarity index 83%
rename from services/tests/servicestests/src/com/android/server/am/ActivityRecordTests.java
rename to services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
index 1015008..b865772 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,18 +14,14 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
-import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
-import static android.content.pm.ActivityInfo.RESIZE_MODE_RESIZEABLE;
-import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
 import static android.view.Display.DEFAULT_DISPLAY;
 
-import static com.android.server.am.ActivityStack.ActivityState.INITIALIZING;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
-import static com.android.server.am.ActivityStack.ActivityState.STOPPED;
-import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_MOVING;
+import static com.android.server.wm.ActivityStack.ActivityState.INITIALIZING;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSING;
+import static com.android.server.wm.ActivityStack.ActivityState.STOPPED;
+import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_MOVING;
 import static com.android.server.policy.WindowManagerPolicy.NAV_BAR_BOTTOM;
 import static com.android.server.policy.WindowManagerPolicy.NAV_BAR_LEFT;
 import static com.android.server.policy.WindowManagerPolicy.NAV_BAR_RIGHT;
@@ -37,11 +33,7 @@
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.any;
-import static org.mockito.Mockito.anyInt;
 import static org.mockito.Mockito.doAnswer;
-import static org.mockito.Mockito.eq;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
 
 import android.app.ActivityOptions;
@@ -52,32 +44,26 @@
 import android.util.MutableBoolean;
 
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 import org.mockito.invocation.InvocationOnMock;
 
 /**
  * Tests for the {@link ActivityRecord} class.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:com.android.server.am.ActivityRecordTests
+ *  atest WmTests:ActivityRecordTests
  */
 @MediumTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class ActivityRecordTests extends ActivityTestsBase {
     private TestActivityStack mStack;
     private TaskRecord mTask;
     private ActivityRecord mActivity;
 
     @Before
-    @Override
     public void setUp() throws Exception {
-        super.setUp();
-
         setupActivityTaskManagerService();
         mStack = new StackBuilder(mSupervisor).build();
         mTask = mStack.getChildAt(0);
@@ -85,26 +71,26 @@
     }
 
     @Test
-    public void testStackCleanupOnClearingTask() throws Exception {
+    public void testStackCleanupOnClearingTask() {
         mActivity.setTask(null);
         assertEquals(mStack.onActivityRemovedFromStackInvocationCount(), 1);
     }
 
     @Test
-    public void testStackCleanupOnActivityRemoval() throws Exception {
+    public void testStackCleanupOnActivityRemoval() {
         mTask.removeActivity(mActivity);
         assertEquals(mStack.onActivityRemovedFromStackInvocationCount(),  1);
     }
 
     @Test
-    public void testStackCleanupOnTaskRemoval() throws Exception {
+    public void testStackCleanupOnTaskRemoval() {
         mStack.removeTask(mTask, null /*reason*/, REMOVE_TASK_MODE_MOVING);
         // Stack should be gone on task removal.
         assertNull(mService.mStackSupervisor.getStack(mStack.mStackId));
     }
 
     @Test
-    public void testNoCleanupMovingActivityInSameStack() throws Exception {
+    public void testNoCleanupMovingActivityInSameStack() {
         final TaskRecord newTask = new TaskBuilder(mService.mStackSupervisor).setStack(mStack)
                 .build();
         mActivity.reparent(newTask, 0, null /*reason*/);
@@ -157,19 +143,19 @@
     }
 
     @Test
-    public void testPositionLimitedAspectRatioNavBarBottom() throws Exception {
+    public void testPositionLimitedAspectRatioNavBarBottom() {
         verifyPositionWithLimitedAspectRatio(NAV_BAR_BOTTOM, new Rect(0, 0, 1000, 2000), 1.5f,
                 new Rect(0, 0, 1000, 1500));
     }
 
     @Test
-    public void testPositionLimitedAspectRatioNavBarLeft() throws Exception {
+    public void testPositionLimitedAspectRatioNavBarLeft() {
         verifyPositionWithLimitedAspectRatio(NAV_BAR_LEFT, new Rect(0, 0, 2000, 1000), 1.5f,
                 new Rect(500, 0, 2000, 1000));
     }
 
     @Test
-    public void testPositionLimitedAspectRatioNavBarRight() throws Exception {
+    public void testPositionLimitedAspectRatioNavBarRight() {
         verifyPositionWithLimitedAspectRatio(NAV_BAR_RIGHT, new Rect(0, 0, 2000, 1000), 1.5f,
                 new Rect(0, 0, 1500, 1000));
     }
@@ -186,7 +172,7 @@
     }
 
     @Test
-    public void testCanBeLaunchedOnDisplay() throws Exception {
+    public void testCanBeLaunchedOnDisplay() {
         mService.mSupportsMultiWindow = true;
         final ActivityRecord activity = new ActivityBuilder(mService).build();
 
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityStackSupervisorTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java
similarity index 91%
rename from services/tests/servicestests/src/com/android/server/am/ActivityStackSupervisorTests.java
rename to services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java
index 8ab2210..a794d6d 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityStackSupervisorTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStackSupervisorTests.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.START_DELIVERED_TO_TOP;
 import static android.app.ActivityManager.START_TASK_TO_FRONT;
@@ -26,9 +26,12 @@
 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_PRIMARY;
 import static android.content.pm.ActivityInfo.FLAG_ALWAYS_FOCUSABLE;
 
-import static com.android.server.am.ActivityDisplay.POSITION_TOP;
-import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
-import static com.android.server.am.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE;
+import static com.android.server.wm.ActivityDisplay.POSITION_TOP;
+import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
+import static com.android.server.wm.ActivityStackSupervisor.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE;
+
+
+import static com.google.common.truth.Truth.assertThat;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -55,11 +58,9 @@
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 
@@ -67,19 +68,15 @@
  * Tests for the {@link ActivityStackSupervisor} class.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:com.android.server.am.ActivityStackSupervisorTests
+ *  atest WmTests:ActivityStackSupervisorTests
  */
 @MediumTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class ActivityStackSupervisorTests extends ActivityTestsBase {
     private ActivityStack mFullscreenStack;
 
     @Before
-    @Override
     public void setUp() throws Exception {
-        super.setUp();
-
         setupActivityTaskManagerService();
         mFullscreenStack = mService.mStackSupervisor.getDefaultDisplay().createStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
@@ -90,7 +87,7 @@
      * should expect {@code null} to be returned in this case.
      */
     @Test
-    public void testRestoringInvalidTask() throws Exception {
+    public void testRestoringInvalidTask() {
         ((TestActivityDisplay) mSupervisor.getDefaultDisplay()).removeAllTasks();
         TaskRecord task = mSupervisor.anyTaskForIdLocked(0 /*taskId*/,
                 MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE, null, false /* onTop */);
@@ -102,7 +99,7 @@
      * activity stack when a new task is added.
      */
     @Test
-    public void testReplacingTaskInPinnedStack() throws Exception {
+    public void testReplacingTaskInPinnedStack() {
         final ActivityRecord firstActivity = new ActivityBuilder(mService).setCreateTask(true)
                 .setStack(mFullscreenStack).build();
         final TaskRecord firstTask = firstActivity.getTask();
@@ -156,7 +153,7 @@
      * Ensures that an activity is removed from the stopping activities list once it is resumed.
      */
     @Test
-    public void testStoppingActivityRemovedWhenResumed() throws Exception {
+    public void testStoppingActivityRemovedWhenResumed() {
         final ActivityRecord firstActivity = new ActivityBuilder(mService).setCreateTask(true)
                 .setStack(mFullscreenStack).build();
         mSupervisor.mStoppingActivities.add(firstActivity);
@@ -169,8 +166,9 @@
     /**
      * Ensures that waiting results are notified of launches.
      */
+    @SuppressWarnings("SynchronizeOnNonFinalField")
     @Test
-    public void testReportWaitingActivityLaunchedIfNeeded() throws Exception {
+    public void testReportWaitingActivityLaunchedIfNeeded() {
         final ActivityRecord firstActivity = new ActivityBuilder(mService).setCreateTask(true)
                 .setStack(mFullscreenStack).build();
 
@@ -181,23 +179,23 @@
             mSupervisor.mWaitingActivityLaunched.add(taskToFrontWait);
             mSupervisor.reportWaitingActivityLaunchedIfNeeded(firstActivity, START_TASK_TO_FRONT);
 
-            assertTrue(mSupervisor.mWaitingActivityLaunched.isEmpty());
+            assertThat(mSupervisor.mWaitingActivityLaunched).isEmpty();
             assertEquals(taskToFrontWait.result, START_TASK_TO_FRONT);
-            assertEquals(taskToFrontWait.who, null);
+            assertNull(taskToFrontWait.who);
 
             final WaitResult deliverToTopWait = new WaitResult();
             mSupervisor.mWaitingActivityLaunched.add(deliverToTopWait);
             mSupervisor.reportWaitingActivityLaunchedIfNeeded(firstActivity,
                     START_DELIVERED_TO_TOP);
 
-            assertTrue(mSupervisor.mWaitingActivityLaunched.isEmpty());
+            assertThat(mSupervisor.mWaitingActivityLaunched).isEmpty();
             assertEquals(deliverToTopWait.result, START_DELIVERED_TO_TOP);
             assertEquals(deliverToTopWait.who, firstActivity.realActivity);
         }
     }
 
     @Test
-    public void testApplySleepTokensLocked() throws Exception {
+    public void testApplySleepTokensLocked() {
         final ActivityDisplay display = mSupervisor.getDefaultDisplay();
         final KeyguardController keyguard = mSupervisor.getKeyguardController();
         final ActivityStack stack = mock(ActivityStack.class);
@@ -253,7 +251,7 @@
      * Verifies that removal of activity with task and stack is done correctly.
      */
     @Test
-    public void testRemovingStackOnAppCrash() throws Exception {
+    public void testRemovingStackOnAppCrash() {
         final ActivityDisplay defaultDisplay = mService.mStackSupervisor.getDefaultDisplay();
         final int originalStackCount = defaultDisplay.getChildCount();
         final ActivityStack stack = mService.mStackSupervisor.getDefaultDisplay().createStack(
@@ -272,7 +270,7 @@
     }
 
     @Test
-    public void testFocusability() throws Exception {
+    public void testFocusability() {
         final ActivityStack stack = mService.mStackSupervisor.getDefaultDisplay().createStack(
                 WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD, true /* onTop */);
         final ActivityRecord activity = new ActivityBuilder(mService).setCreateTask(true)
@@ -316,7 +314,7 @@
      * primary stack.
      */
     @Test
-    public void testSplitScreenPrimaryChosenWhenTopActivityLaunchedToSecondary() throws Exception {
+    public void testSplitScreenPrimaryChosenWhenTopActivityLaunchedToSecondary() {
         // Create primary split-screen stack with a task and an activity.
         final ActivityStack primaryStack = mService.mStackSupervisor.getDefaultDisplay()
                 .createStack(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD,
@@ -339,9 +337,9 @@
      * {@link android.app.IActivityTaskManager#resizeDockedStack} as expect.
      */
     @Test
-    public void testResizeDockedStackForSplitScreenPrimary() throws Exception {
-        final Rect TASK_SIZE = new Rect(0, 0, 600, 600);
-        final Rect STACK_SIZE = new Rect(0, 0, 300, 300);
+    public void testResizeDockedStackForSplitScreenPrimary() {
+        final Rect taskSize = new Rect(0, 0, 600, 600);
+        final Rect stackSize = new Rect(0, 0, 300, 300);
 
         // Create primary split-screen stack with a task.
         final ActivityStack primaryStack = mService.mStackSupervisor.getDefaultDisplay()
@@ -350,18 +348,18 @@
         final TaskRecord task = new TaskBuilder(mSupervisor).setStack(primaryStack).build();
 
         // Resize dock stack.
-        mService.resizeDockedStack(STACK_SIZE, TASK_SIZE, null, null, null);
+        mService.resizeDockedStack(stackSize, taskSize, null, null, null);
 
         // Verify dock stack & its task bounds if is equal as resized result.
-        assertEquals(primaryStack.getBounds(), STACK_SIZE);
-        assertEquals(task.getBounds(), TASK_SIZE);
+        assertEquals(primaryStack.getBounds(), stackSize);
+        assertEquals(task.getBounds(), taskSize);
     }
 
     /**
      * Verify that home stack would be moved to front when the top activity is Recents.
      */
     @Test
-    public void testFindTaskToMoveToFrontWhenRecentsOnTop() throws Exception {
+    public void testFindTaskToMoveToFrontWhenRecentsOnTop() {
         // Create stack/task on default display.
         final ActivityDisplay display = mSupervisor.getDefaultDisplay();
         final TestActivityStack targetStack = new StackBuilder(mSupervisor).setOnTop(false).build();
@@ -383,7 +381,7 @@
      * Recents.
      */
     @Test
-    public void testFindTaskToMoveToFrontWhenRecentsOnOtherDisplay() throws Exception {
+    public void testFindTaskToMoveToFrontWhenRecentsOnOtherDisplay() {
         // Create stack/task on default display.
         final ActivityDisplay display = mSupervisor.getDefaultDisplay();
         final ActivityStack targetStack = display.createStack(WINDOWING_MODE_FULLSCREEN,
@@ -410,7 +408,7 @@
      * the stack is the top focused.
      */
     @Test
-    public void testResumeActivityWhenNonTopmostStackIsTopFocused() throws Exception {
+    public void testResumeActivityWhenNonTopmostStackIsTopFocused() {
         // Create a stack at bottom.
         final ActivityDisplay display = mSupervisor.getDefaultDisplay();
         final ActivityStack targetStack = spy(display.createStack(WINDOWING_MODE_FULLSCREEN,
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityStackTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
similarity index 83%
rename from services/tests/servicestests/src/com/android/server/am/ActivityStackTests.java
rename to services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
index 839792d..974e285 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityStackTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
@@ -26,12 +26,14 @@
 import static android.app.WindowConfiguration.WINDOWING_MODE_SPLIT_SCREEN_SECONDARY;
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
 
-import static com.android.server.am.ActivityStack.ActivityState.STOPPING;
-import static com.android.server.am.ActivityStack.ActivityState.DESTROYING;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSED;
-import static com.android.server.am.ActivityStack.ActivityState.PAUSING;
-import static com.android.server.am.ActivityStack.ActivityState.RESUMED;
-import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
+import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSED;
+import static com.android.server.wm.ActivityStack.ActivityState.PAUSING;
+import static com.android.server.wm.ActivityStack.ActivityState.RESUMED;
+import static com.android.server.wm.ActivityStack.ActivityState.STOPPING;
+import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
+
+import static com.google.common.truth.Truth.assertThat;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -52,31 +54,25 @@
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link ActivityStack} class.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:com.android.server.am.ActivityStackTests
+ *  atest WmTests:ActivityStackTests
  */
 @SmallTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class ActivityStackTests extends ActivityTestsBase {
     private ActivityDisplay mDefaultDisplay;
     private ActivityStack mStack;
     private TaskRecord mTask;
 
     @Before
-    @Override
     public void setUp() throws Exception {
-        super.setUp();
-
         setupActivityTaskManagerService();
         mDefaultDisplay = mSupervisor.getDefaultDisplay();
         mStack = spy(mDefaultDisplay.createStack(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD,
@@ -85,14 +81,14 @@
     }
 
     @Test
-    public void testEmptyTaskCleanupOnRemove() throws Exception {
+    public void testEmptyTaskCleanupOnRemove() {
         assertNotNull(mTask.getWindowContainerController());
         mStack.removeTask(mTask, "testEmptyTaskCleanupOnRemove", REMOVE_TASK_MODE_DESTROYING);
         assertNull(mTask.getWindowContainerController());
     }
 
     @Test
-    public void testOccupiedTaskCleanupOnRemove() throws Exception {
+    public void testOccupiedTaskCleanupOnRemove() {
         final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build();
         assertNotNull(mTask.getWindowContainerController());
         mStack.removeTask(mTask, "testOccupiedTaskCleanupOnRemove", REMOVE_TASK_MODE_DESTROYING);
@@ -100,13 +96,13 @@
     }
 
     @Test
-    public void testResumedActivity() throws Exception {
+    public void testResumedActivity() {
         final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build();
-        assertEquals(mStack.getResumedActivity(), null);
+        assertNull(mStack.getResumedActivity());
         r.setState(RESUMED, "testResumedActivity");
-        assertEquals(mStack.getResumedActivity(), r);
+        assertEquals(r, mStack.getResumedActivity());
         r.setState(PAUSING, "testResumedActivity");
-        assertEquals(mStack.getResumedActivity(), null);
+        assertNull(mStack.getResumedActivity());
     }
 
     @Test
@@ -114,7 +110,7 @@
         final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build();
         // Ensure moving task between two stacks updates resumed activity
         r.setState(RESUMED, "testResumedActivityFromTaskReparenting");
-        assertEquals(mStack.getResumedActivity(), r);
+        assertEquals(r, mStack.getResumedActivity());
 
         final ActivityStack destStack = mService.mStackSupervisor.getDefaultDisplay().createStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
@@ -123,8 +119,8 @@
                 false /* animate */, true /* deferResume*/,
                 "testResumedActivityFromTaskReparenting");
 
-        assertEquals(mStack.getResumedActivity(), null);
-        assertEquals(destStack.getResumedActivity(), r);
+        assertNull(mStack.getResumedActivity());
+        assertEquals(r, destStack.getResumedActivity());
     }
 
     @Test
@@ -132,7 +128,7 @@
         final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build();
         // Ensure moving task between two stacks updates resumed activity
         r.setState(RESUMED, "testResumedActivityFromActivityReparenting");
-        assertEquals(mStack.getResumedActivity(), r);
+        assertEquals(r, mStack.getResumedActivity());
 
         final ActivityStack destStack = mService.mStackSupervisor.getDefaultDisplay().createStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
@@ -141,60 +137,60 @@
         mTask.removeActivity(r);
         destTask.addActivityToTop(r);
 
-        assertEquals(mStack.getResumedActivity(), null);
-        assertEquals(destStack.getResumedActivity(), r);
+        assertNull(mStack.getResumedActivity());
+        assertEquals(r, destStack.getResumedActivity());
     }
 
     @Test
-    public void testPrimarySplitScreenRestoresWhenMovedToBack() throws Exception {
+    public void testPrimarySplitScreenRestoresWhenMovedToBack() {
         // Create primary splitscreen stack. This will create secondary stacks and places the
         // existing fullscreen stack on the bottom.
         final ActivityStack primarySplitScreen = mDefaultDisplay.createStack(
                 WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD, true /* onTop */);
 
         // Assert windowing mode.
-        assertEquals(primarySplitScreen.getWindowingMode(), WINDOWING_MODE_SPLIT_SCREEN_PRIMARY);
+        assertEquals(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, primarySplitScreen.getWindowingMode());
 
         // Move primary to back.
         primarySplitScreen.moveToBack("testPrimarySplitScreenToFullscreenWhenMovedToBack",
                 null /* task */);
 
         // Assert that stack is at the bottom.
-        assertEquals(mDefaultDisplay.getIndexOf(primarySplitScreen), 0);
+        assertEquals(0, mDefaultDisplay.getIndexOf(primarySplitScreen));
 
         // Ensure no longer in splitscreen.
-        assertEquals(primarySplitScreen.getWindowingMode(), WINDOWING_MODE_FULLSCREEN);
+        assertEquals(WINDOWING_MODE_FULLSCREEN, primarySplitScreen.getWindowingMode());
 
         // Ensure that the override mode is restored to undefined
-        assertEquals(primarySplitScreen.getOverrideWindowingMode(), WINDOWING_MODE_UNDEFINED);
+        assertEquals(WINDOWING_MODE_UNDEFINED, primarySplitScreen.getOverrideWindowingMode());
     }
 
     @Test
-    public void testPrimarySplitScreenRestoresPreviousWhenMovedToBack() throws Exception {
+    public void testPrimarySplitScreenRestoresPreviousWhenMovedToBack() {
         // This time, start with a fullscreen activitystack
         final ActivityStack primarySplitScreen = mDefaultDisplay.createStack(
-            WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
+                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
 
         primarySplitScreen.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY);
 
         // Assert windowing mode.
-        assertEquals(primarySplitScreen.getWindowingMode(), WINDOWING_MODE_SPLIT_SCREEN_PRIMARY);
+        assertEquals(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, primarySplitScreen.getWindowingMode());
 
         // Move primary to back.
         primarySplitScreen.moveToBack("testPrimarySplitScreenToFullscreenWhenMovedToBack",
-            null /* task */);
+                null /* task */);
 
         // Assert that stack is at the bottom.
-        assertEquals(mDefaultDisplay.getIndexOf(primarySplitScreen), 0);
+        assertEquals(0, mDefaultDisplay.getIndexOf(primarySplitScreen));
 
         // Ensure that the override mode is restored to what it was (fullscreen)
-        assertEquals(primarySplitScreen.getOverrideWindowingMode(), WINDOWING_MODE_FULLSCREEN);
+        assertEquals(WINDOWING_MODE_FULLSCREEN, primarySplitScreen.getOverrideWindowingMode());
     }
 
     @Test
-    public void testStackInheritsDisplayWindowingMode() throws Exception {
+    public void testStackInheritsDisplayWindowingMode() {
         final ActivityStack primarySplitScreen = mDefaultDisplay.createStack(
-            WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD, true /* onTop */);
+                WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD, true /* onTop */);
 
         assertEquals(WINDOWING_MODE_FULLSCREEN, primarySplitScreen.getWindowingMode());
         assertEquals(WINDOWING_MODE_UNDEFINED, primarySplitScreen.getOverrideWindowingMode());
@@ -205,9 +201,9 @@
     }
 
     @Test
-    public void testStackOverridesDisplayWindowingMode() throws Exception {
+    public void testStackOverridesDisplayWindowingMode() {
         final ActivityStack primarySplitScreen = mDefaultDisplay.createStack(
-            WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD, true /* onTop */);
+                WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_STANDARD, true /* onTop */);
 
         assertEquals(WINDOWING_MODE_FULLSCREEN, primarySplitScreen.getWindowingMode());
         assertEquals(WINDOWING_MODE_UNDEFINED, primarySplitScreen.getOverrideWindowingMode());
@@ -221,7 +217,7 @@
     }
 
     @Test
-    public void testStopActivityWhenActivityDestroyed() throws Exception {
+    public void testStopActivityWhenActivityDestroyed() {
         final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build();
         r.info.flags |= ActivityInfo.FLAG_NO_HISTORY;
         mStack.moveToFront("testStopActivityWithDestroy");
@@ -231,7 +227,7 @@
     }
 
     @Test
-    public void testFindTaskWithOverlay() throws Exception {
+    public void testFindTaskWithOverlay() {
         final ActivityRecord r = new ActivityBuilder(mService)
                 .setCreateTask(true)
                 .setStack(mStack)
@@ -247,8 +243,8 @@
                 new ActivityStackSupervisor.FindTaskResult();
         mStack.findTaskLocked(r, result);
 
-        assertEquals(task.getTopActivity(false /* includeOverlays */), r);
-        assertEquals(task.getTopActivity(true /* includeOverlays */), taskOverlay);
+        assertEquals(r, task.getTopActivity(false /* includeOverlays */));
+        assertEquals(taskOverlay, task.getTopActivity(true /* includeOverlays */));
         assertNotNull(result.mRecord);
     }
 
@@ -273,7 +269,7 @@
     }
 
     @Test
-    public void testShouldBeVisible_Fullscreen() throws Exception {
+    public void testShouldBeVisible_Fullscreen() {
         final TestActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay,
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */);
         final ActivityStack pinnedStack = createStackForShouldBeVisibleTest(mDefaultDisplay,
@@ -298,14 +294,16 @@
     }
 
     @Test
-    public void testShouldBeVisible_SplitScreen() throws Exception {
+    public void testShouldBeVisible_SplitScreen() {
         final TestActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay,
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */);
         // Home stack should always be fullscreen for this test.
         homeStack.setSupportsSplitScreen(false);
-        final TestActivityStack splitScreenPrimary = createStackForShouldBeVisibleTest(mDefaultDisplay,
+        final TestActivityStack splitScreenPrimary =
+                createStackForShouldBeVisibleTest(mDefaultDisplay,
                 WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD, true /* onTop */);
-        final TestActivityStack splitScreenSecondary = createStackForShouldBeVisibleTest(mDefaultDisplay,
+        final TestActivityStack splitScreenSecondary =
+                createStackForShouldBeVisibleTest(mDefaultDisplay,
                 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY, ACTIVITY_TYPE_STANDARD, true /* onTop */);
 
         // Home stack shouldn't be visible if both halves of split-screen are opaque.
@@ -321,7 +319,8 @@
         assertTrue(splitScreenPrimary.shouldBeVisible(null /* starting */));
         assertTrue(splitScreenSecondary.shouldBeVisible(null /* starting */));
 
-        final TestActivityStack splitScreenSecondary2 = createStackForShouldBeVisibleTest(mDefaultDisplay,
+        final TestActivityStack splitScreenSecondary2 =
+                createStackForShouldBeVisibleTest(mDefaultDisplay,
                 WINDOWING_MODE_SPLIT_SCREEN_SECONDARY, ACTIVITY_TYPE_STANDARD, true /* onTop */);
         // First split-screen secondary shouldn't be visible behind another opaque split-split
         // secondary.
@@ -364,7 +363,7 @@
     }
 
     @Test
-    public void testShouldBeVisible_Finishing() throws Exception {
+    public void testShouldBeVisible_Finishing() {
         final TestActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay,
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */);
         final TestActivityStack translucentStack = createStackForShouldBeVisibleTest(
@@ -403,9 +402,9 @@
 
         // Ensure that we don't move the home stack if it is already behind the top fullscreen stack
         int homeStackIndex = mDefaultDisplay.getIndexOf(homeStack);
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack);
+        assertEquals(fullscreenStack, mDefaultDisplay.getStackAbove(homeStack));
         mDefaultDisplay.moveStackBehindBottomMostVisibleStack(homeStack);
-        assertTrue(mDefaultDisplay.getIndexOf(homeStack) == homeStackIndex);
+        assertEquals(homeStackIndex, mDefaultDisplay.getIndexOf(homeStack));
     }
 
     @Test
@@ -422,9 +421,9 @@
 
         // Ensure that we don't move the home stack if it is already behind the top fullscreen stack
         int homeStackIndex = mDefaultDisplay.getIndexOf(homeStack);
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack);
+        assertEquals(fullscreenStack, mDefaultDisplay.getStackAbove(homeStack));
         mDefaultDisplay.moveStackBehindBottomMostVisibleStack(homeStack);
-        assertTrue(mDefaultDisplay.getIndexOf(homeStack) == homeStackIndex);
+        assertEquals(homeStackIndex, mDefaultDisplay.getIndexOf(homeStack));
     }
 
     @Test
@@ -441,9 +440,9 @@
 
         // Ensure we don't move the home stack if it is already on top
         int homeStackIndex = mDefaultDisplay.getIndexOf(homeStack);
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == null);
+        assertNull(mDefaultDisplay.getStackAbove(homeStack));
         mDefaultDisplay.moveStackBehindBottomMostVisibleStack(homeStack);
-        assertTrue(mDefaultDisplay.getIndexOf(homeStack) == homeStackIndex);
+        assertEquals(homeStackIndex, mDefaultDisplay.getIndexOf(homeStack));
     }
 
     @Test
@@ -467,13 +466,14 @@
 
         // Ensure that we move the home stack behind the bottom most fullscreen stack, ignoring the
         // pinned stack
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack1);
+        assertEquals(fullscreenStack1, mDefaultDisplay.getStackAbove(homeStack));
         mDefaultDisplay.moveStackBehindBottomMostVisibleStack(homeStack);
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack2);
+        assertEquals(fullscreenStack2, mDefaultDisplay.getStackAbove(homeStack));
     }
 
     @Test
-    public void testMoveHomeStackBehindBottomMostVisibleStack_MoveHomeBehindFullscreenAndTranslucent() {
+    public void
+            testMoveHomeStackBehindBottomMostVisibleStack_MoveHomeBehindFullscreenAndTranslucent() {
         mDefaultDisplay.removeChild(mStack);
 
         final TestActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay,
@@ -491,9 +491,9 @@
 
         // Ensure that we move the home stack behind the bottom most non-translucent fullscreen
         // stack
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack1);
+        assertEquals(fullscreenStack1, mDefaultDisplay.getStackAbove(homeStack));
         mDefaultDisplay.moveStackBehindBottomMostVisibleStack(homeStack);
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack1);
+        assertEquals(fullscreenStack1, mDefaultDisplay.getStackAbove(homeStack));
     }
 
     @Test
@@ -516,7 +516,7 @@
         // Ensure we don't move the home stack behind itself
         int homeStackIndex = mDefaultDisplay.getIndexOf(homeStack);
         mDefaultDisplay.moveStackBehindStack(homeStack, homeStack);
-        assertTrue(mDefaultDisplay.getIndexOf(homeStack) == homeStackIndex);
+        assertEquals(homeStackIndex, mDefaultDisplay.getIndexOf(homeStack));
     }
 
     @Test
@@ -539,13 +539,13 @@
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */);
 
         mDefaultDisplay.moveStackBehindStack(homeStack, fullscreenStack1);
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack1);
+        assertEquals(fullscreenStack1, mDefaultDisplay.getStackAbove(homeStack));
         mDefaultDisplay.moveStackBehindStack(homeStack, fullscreenStack2);
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack2);
+        assertEquals(fullscreenStack2, mDefaultDisplay.getStackAbove(homeStack));
         mDefaultDisplay.moveStackBehindStack(homeStack, fullscreenStack4);
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack4);
+        assertEquals(fullscreenStack4, mDefaultDisplay.getStackAbove(homeStack));
         mDefaultDisplay.moveStackBehindStack(homeStack, fullscreenStack2);
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == fullscreenStack2);
+        assertEquals(fullscreenStack2, mDefaultDisplay.getStackAbove(homeStack));
     }
 
     @Test
@@ -554,7 +554,7 @@
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */);
         final ActivityStack pinnedStack = createStackForShouldBeVisibleTest(mDefaultDisplay,
                 WINDOWING_MODE_PINNED, ACTIVITY_TYPE_STANDARD, true /* onTop */);
-        assertTrue(mDefaultDisplay.getStackAbove(homeStack) == pinnedStack);
+        assertEquals(pinnedStack, mDefaultDisplay.getStackAbove(homeStack));
 
         final TestActivityStack alwaysOnTopStack = createStackForShouldBeVisibleTest(
                 mDefaultDisplay, WINDOWING_MODE_FREEFORM, ACTIVITY_TYPE_STANDARD,
@@ -562,13 +562,13 @@
         alwaysOnTopStack.setAlwaysOnTop(true);
         assertTrue(alwaysOnTopStack.isAlwaysOnTop());
         // Ensure (non-pinned) always on top stack is put below pinned stack.
-        assertTrue(mDefaultDisplay.getStackAbove(alwaysOnTopStack) == pinnedStack);
+        assertEquals(pinnedStack, mDefaultDisplay.getStackAbove(alwaysOnTopStack));
 
         final TestActivityStack nonAlwaysOnTopStack = createStackForShouldBeVisibleTest(
                 mDefaultDisplay, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD,
                 true /* onTop */);
         // Ensure non always on top stack is put below always on top stacks.
-        assertTrue(mDefaultDisplay.getStackAbove(nonAlwaysOnTopStack) == alwaysOnTopStack);
+        assertEquals(alwaysOnTopStack, mDefaultDisplay.getStackAbove(nonAlwaysOnTopStack));
 
         final TestActivityStack alwaysOnTopStack2 = createStackForShouldBeVisibleTest(
                 mDefaultDisplay, WINDOWING_MODE_FREEFORM, ACTIVITY_TYPE_STANDARD,
@@ -576,25 +576,25 @@
         alwaysOnTopStack2.setAlwaysOnTop(true);
         assertTrue(alwaysOnTopStack2.isAlwaysOnTop());
         // Ensure newly created always on top stack is placed above other all always on top stacks.
-        assertTrue(mDefaultDisplay.getStackAbove(alwaysOnTopStack2) == pinnedStack);
+        assertEquals(pinnedStack, mDefaultDisplay.getStackAbove(alwaysOnTopStack2));
 
         alwaysOnTopStack2.setAlwaysOnTop(false);
         // Ensure, when always on top is turned off for a stack, the stack is put just below all
         // other always on top stacks.
-        assertTrue(mDefaultDisplay.getStackAbove(alwaysOnTopStack2) == alwaysOnTopStack);
+        assertEquals(alwaysOnTopStack, mDefaultDisplay.getStackAbove(alwaysOnTopStack2));
         alwaysOnTopStack2.setAlwaysOnTop(true);
 
         // Ensure always on top state changes properly when windowing mode changes.
         alwaysOnTopStack2.setWindowingMode(WINDOWING_MODE_FULLSCREEN);
         assertFalse(alwaysOnTopStack2.isAlwaysOnTop());
-        assertTrue(mDefaultDisplay.getStackAbove(alwaysOnTopStack2) == alwaysOnTopStack);
+        assertEquals(alwaysOnTopStack, mDefaultDisplay.getStackAbove(alwaysOnTopStack2));
         alwaysOnTopStack2.setWindowingMode(WINDOWING_MODE_FREEFORM);
         assertTrue(alwaysOnTopStack2.isAlwaysOnTop());
-        assertTrue(mDefaultDisplay.getStackAbove(alwaysOnTopStack2) == pinnedStack);
+        assertEquals(pinnedStack, mDefaultDisplay.getStackAbove(alwaysOnTopStack2));
     }
 
     @Test
-    public void testSplitScreenMoveToFront() throws Exception {
+    public void testSplitScreenMoveToFront() {
         final TestActivityStack splitScreenPrimary = createStackForShouldBeVisibleTest(
                 mDefaultDisplay, WINDOWING_MODE_SPLIT_SCREEN_PRIMARY, ACTIVITY_TYPE_STANDARD,
                 true /* onTop */);
@@ -619,6 +619,7 @@
         assertFalse(assistantStack.shouldBeVisible(null /* starting */));
     }
 
+    @SuppressWarnings("TypeParameterUnusedInFormals")
     private <T extends ActivityStack> T createStackForShouldBeVisibleTest(
             ActivityDisplay display, int windowingMode, int activityType, boolean onTop) {
         final T stack;
@@ -639,7 +640,7 @@
     }
 
     @Test
-    public void testFinishDisabledPackageActivities() throws Exception {
+    public void testFinishDisabledPackageActivities() {
         final ActivityRecord firstActivity = new ActivityBuilder(mService).setTask(mTask).build();
         final ActivityRecord secondActivity = new ActivityBuilder(mService).setTask(mTask).build();
 
@@ -648,17 +649,17 @@
         secondActivity.mTaskOverlay = true;
         secondActivity.app = null;
 
-        assertEquals(mTask.mActivities.size(), 2);
+        assertEquals(2, mTask.mActivities.size());
 
         mStack.finishDisabledPackageActivitiesLocked(firstActivity.packageName, null,
                 true /* doit */, true /* evenPersistent */, UserHandle.USER_ALL);
 
-        assertTrue(mTask.mActivities.isEmpty());
-        assertTrue(mStack.getAllTasks().isEmpty());
+        assertThat(mTask.mActivities).isEmpty();
+        assertThat(mStack.getAllTasks()).isEmpty();
     }
 
     @Test
-    public void testHandleAppDied() throws Exception {
+    public void testHandleAppDied() {
         final ActivityRecord firstActivity = new ActivityBuilder(mService).setTask(mTask).build();
         final ActivityRecord secondActivity = new ActivityBuilder(mService).setTask(mTask).build();
 
@@ -671,12 +672,12 @@
         // second activity will be immediately removed as it has no state.
         secondActivity.haveState = false;
 
-        assertEquals(mTask.mActivities.size(), 2);
+        assertEquals(2, mTask.mActivities.size());
 
         mStack.handleAppDiedLocked(secondActivity.app);
 
-        assertTrue(mTask.mActivities.isEmpty());
-        assertTrue(mStack.getAllTasks().isEmpty());
+        assertThat(mTask.mActivities).isEmpty();
+        assertThat(mStack.getAllTasks()).isEmpty();
     }
 
     @Test
@@ -693,7 +694,7 @@
         stack2.getTopActivity().visible = true;
         final ActivityRecord activity2 = finishCurrentActivity(stack2);
         assertEquals(STOPPING, activity2.getState());
-        assertTrue(mSupervisor.mStoppingActivities.contains(activity2));
+        assertThat(mSupervisor.mStoppingActivities).contains(activity2);
 
         // The display becomes empty. Since there is no next activity to be idle, the activity
         // should be destroyed immediately with updating configuration to restore original state.
@@ -714,7 +715,7 @@
     }
 
     @Test
-    public void testShouldSleepActivities() throws Exception {
+    public void testShouldSleepActivities() {
         // When focused activity and keyguard is going away, we should not sleep regardless
         // of the display state
         verifyShouldSleepActivities(true /* focusedStack */, true /*keyguardGoingAway*/,
@@ -732,7 +733,7 @@
     }
 
     @Test
-    public void testStackOrderChangedOnRemoveStack() throws Exception {
+    public void testStackOrderChangedOnRemoveStack() {
         StackOrderChangedListener listener = new StackOrderChangedListener();
         mDefaultDisplay.registerStackOrderChangedListener(listener);
         try {
@@ -740,11 +741,11 @@
         } finally {
             mDefaultDisplay.unregisterStackOrderChangedListener(listener);
         }
-        assertTrue(listener.changed);
+        assertTrue(listener.mChanged);
     }
 
     @Test
-    public void testStackOrderChangedOnAddPositionStack() throws Exception {
+    public void testStackOrderChangedOnAddPositionStack() {
         mDefaultDisplay.removeChild(mStack);
 
         StackOrderChangedListener listener = new StackOrderChangedListener();
@@ -754,11 +755,11 @@
         } finally {
             mDefaultDisplay.unregisterStackOrderChangedListener(listener);
         }
-        assertTrue(listener.changed);
+        assertTrue(listener.mChanged);
     }
 
     @Test
-    public void testStackOrderChangedOnPositionStack() throws Exception {
+    public void testStackOrderChangedOnPositionStack() {
         StackOrderChangedListener listener = new StackOrderChangedListener();
         try {
             final TestActivityStack fullscreenStack1 = createStackForShouldBeVisibleTest(
@@ -769,7 +770,7 @@
         } finally {
             mDefaultDisplay.unregisterStackOrderChangedListener(listener);
         }
-        assertTrue(listener.changed);
+        assertTrue(listener.mChanged);
     }
 
     private void verifyShouldSleepActivities(boolean focusedStack,
@@ -785,12 +786,13 @@
         assertEquals(expected, mStack.shouldSleepActivities());
     }
 
-    private class StackOrderChangedListener implements ActivityDisplay.OnStackOrderChangedListener {
-        boolean changed = false;
+    private static class StackOrderChangedListener
+            implements ActivityDisplay.OnStackOrderChangedListener {
+        public boolean mChanged = false;
 
         @Override
         public void onStackOrderChanged() {
-            changed = true;
+            mChanged = true;
         }
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityStartControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java
similarity index 87%
rename from services/tests/servicestests/src/com/android/server/am/ActivityStartControllerTests.java
rename to services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java
index e1ebbcf..e8de05c 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityStartControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStartControllerTests.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FULLSCREEN;
@@ -32,13 +32,12 @@
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
-import com.android.server.am.ActivityStackSupervisor.PendingActivityLaunch;
-import com.android.server.am.ActivityStarter.Factory;
+import com.android.server.wm.ActivityStackSupervisor.PendingActivityLaunch;
+import com.android.server.wm.ActivityStarter.Factory;
 
+import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.Random;
 
@@ -46,20 +45,17 @@
  * Tests for the {@link ActivityStartController} class.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:ActivityStartControllerTests
+ *  atest WmTests:ActivityStartControllerTests
  */
 @SmallTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class ActivityStartControllerTests extends ActivityTestsBase {
-    private ActivityTaskManagerService mService;
     private ActivityStartController mController;
     private Factory mFactory;
     private ActivityStarter mStarter;
 
-    @Override
+    @Before
     public void setUp() throws Exception {
-        super.setUp();
         mService = createActivityTaskManagerService();
         mFactory = mock(Factory.class);
         mController = new ActivityStartController(mService, mService.mStackSupervisor, mFactory);
@@ -100,7 +96,7 @@
      * Ensures instances are recycled after execution.
      */
     @Test
-    public void testRecycling() throws Exception {
+    public void testRecycling() {
         final Intent intent = new Intent();
         final ActivityStarter optionStarter = new ActivityStarter(mController, mService,
                 mService.mStackSupervisor, mock(ActivityStartInterceptor.class));
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityStartInterceptorTest.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStartInterceptorTest.java
similarity index 94%
rename from services/tests/servicestests/src/com/android/server/am/ActivityStartInterceptorTest.java
rename to services/tests/wmtests/src/com/android/server/wm/ActivityStartInterceptorTest.java
index 270d394..dda077e 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityStartInterceptorTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStartInterceptorTest.java
@@ -1,20 +1,20 @@
 /*
- * Copyright 2017, The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.content.pm.ApplicationInfo.FLAG_SUSPENDED;
 
@@ -48,6 +48,7 @@
 import com.android.internal.app.SuspendedAppActivity;
 import com.android.internal.app.UnlaunchableAppActivity;
 import com.android.server.LocalServices;
+import com.android.server.am.ActivityManagerService;
 import com.android.server.pm.PackageManagerService;
 
 import org.junit.Before;
@@ -60,10 +61,10 @@
  * Unit tests for {@link ActivityStartInterceptorTest}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:com.android.server.am.ActivityStartInterceptorTest
+ *  atest WmTests:ActivityStartInterceptorTest
  */
-@Presubmit
 @SmallTest
+@Presubmit
 public class ActivityStartInterceptorTest {
     private static final int TEST_USER_ID = 1;
     private static final int TEST_REAL_CALLING_UID = 2;
@@ -133,8 +134,8 @@
         // Mock KeyguardManager
         when(mContext.getSystemService(Context.KEYGUARD_SERVICE)).thenReturn(mKeyguardManager);
         when(mKeyguardManager.createConfirmDeviceCredentialIntent(
-                nullable(CharSequence.class), nullable(CharSequence.class), eq(TEST_USER_ID))).
-                thenReturn(CONFIRM_CREDENTIALS_INTENT);
+                nullable(CharSequence.class), nullable(CharSequence.class), eq(TEST_USER_ID)))
+                .thenReturn(CONFIRM_CREDENTIALS_INTENT);
 
         // Mock PackageManager
         when(mService.getPackageManager()).thenReturn(mPackageManager);
@@ -221,8 +222,8 @@
         assertTrue(mInterceptor.intercept(null, null, mAInfo, null, null, 0, 0, null));
 
         // THEN the returned intent is the harmful app warning intent
-        assertTrue(mInterceptor.mIntent.getComponent().getClassName().equals(
-                HarmfulAppWarningActivity.class.getName()));
+        assertEquals(HarmfulAppWarningActivity.class.getName(),
+                mInterceptor.mIntent.getComponent().getClassName());
     }
 
     @Test
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
similarity index 95%
rename from services/tests/servicestests/src/com/android/server/am/ActivityStarterTests.java
rename to services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
index fb11a04..f7d7ad6 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityStarterTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.START_ABORTED;
 import static android.app.ActivityManager.START_CLASS_NOT_FOUND;
@@ -36,12 +36,13 @@
 import static android.content.Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED;
 import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_TASK;
 
-import static com.android.server.am.ActivityDisplay.POSITION_BOTTOM;
-import static com.android.server.am.ActivityDisplay.POSITION_TOP;
-import static com.android.server.am.ActivityTaskManagerService.ANIMATE;
+import static com.android.server.wm.ActivityDisplay.POSITION_BOTTOM;
+import static com.android.server.wm.ActivityDisplay.POSITION_TOP;
+import static com.android.server.wm.ActivityTaskManagerService.ANIMATE;
+
+import static com.google.common.truth.Truth.assertThat;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.ArgumentMatchers.anyBoolean;
 import static org.mockito.ArgumentMatchers.anyInt;
@@ -74,23 +75,21 @@
 import android.view.Gravity;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
-import com.android.server.am.LaunchParamsController.LaunchParamsModifier;
-import com.android.server.am.TaskRecord.TaskRecordFactory;
+import com.android.server.wm.LaunchParamsController.LaunchParamsModifier;
+import com.android.server.wm.TaskRecord.TaskRecordFactory;
 
+import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link ActivityStarter} class.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:ActivityStarterTests
+ *  atest WmTests:ActivityStarterTests
  */
 @SmallTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class ActivityStarterTests extends ActivityTestsBase {
     private ActivityStarter mStarter;
     private ActivityStartController mController;
@@ -112,9 +111,8 @@
     private static final int FAKE_REAL_CALLING_UID = 667;
     private static final String FAKE_CALLING_PACKAGE = "com.whatever.dude";
 
-    @Override
+    @Before
     public void setUp() throws Exception {
-        super.setUp();
         setupActivityTaskManagerService();
         mController = mock(ActivityStartController.class);
         mActivityMetricsLogger = mock(ActivityMetricsLogger.class);
@@ -124,7 +122,7 @@
     }
 
     @Test
-    public void testUpdateLaunchBounds() throws Exception {
+    public void testUpdateLaunchBounds() {
         // When in a non-resizeable stack, the task bounds should be updated.
         final TaskRecord task = new TaskBuilder(mService.mStackSupervisor)
                 .setStack(mService.mStackSupervisor.getDefaultDisplay().createStack(
@@ -133,7 +131,7 @@
         final Rect bounds = new Rect(10, 10, 100, 100);
 
         mStarter.updateBounds(task, bounds);
-        assertEquals(task.getOverrideBounds(), bounds);
+        assertEquals(bounds, task.getOverrideBounds());
         assertEquals(new Rect(), task.getStack().getOverrideBounds());
 
         // When in a resizeable stack, the stack bounds should be updated as well.
@@ -141,7 +139,7 @@
                 .setStack(mService.mStackSupervisor.getDefaultDisplay().createStack(
                         WINDOWING_MODE_PINNED, ACTIVITY_TYPE_STANDARD, true /* onTop */))
                 .build();
-        assertTrue(task2.getStack() instanceof PinnedActivityStack);
+        assertThat((Object) task2.getStack()).isInstanceOf(PinnedActivityStack.class);
         mStarter.updateBounds(task2, bounds);
 
         verify(mService, times(1)).resizeStack(eq(task2.getStack().mStackId),
@@ -149,15 +147,15 @@
 
         // In the case of no animation, the stack and task bounds should be set immediately.
         if (!ANIMATE) {
-            assertEquals(task2.getStack().getOverrideBounds(), bounds);
-            assertEquals(task2.getOverrideBounds(), bounds);
+            assertEquals(bounds, task2.getStack().getOverrideBounds());
+            assertEquals(bounds, task2.getOverrideBounds());
         } else {
-            assertEquals(task2.getOverrideBounds(), new Rect());
+            assertEquals(new Rect(), task2.getOverrideBounds());
         }
     }
 
     @Test
-    public void testStartActivityPreconditions() throws Exception {
+    public void testStartActivityPreconditions() {
         verifyStartActivityPreconditions(PRECONDITION_NO_CALLER_APP, START_PERMISSION_DENIED);
         verifyStartActivityPreconditions(PRECONDITION_NO_INTENT_COMPONENT,
                 START_INTENT_NOT_RESOLVED);
@@ -211,7 +209,7 @@
         final WindowProcessController wpc =
                 containsConditions(preconditions, PRECONDITION_NO_CALLER_APP)
                 ? null : new WindowProcessController(
-                        service, mock(ApplicationInfo.class),null, 0, -1, null, null);
+                        service, mock(ApplicationInfo.class), null, 0, -1, null, null);
         doReturn(wpc).when(service).getProcessController(anyObject());
 
         final Intent intent = new Intent();
@@ -250,7 +248,7 @@
                     anyInt(), anyInt(), anyInt(), anyInt(), any());
         }
 
-        if (containsConditions(preconditions,PRECONDITION_CANNOT_START_ANY_ACTIVITY)) {
+        if (containsConditions(preconditions, PRECONDITION_CANNOT_START_ANY_ACTIVITY)) {
             doReturn(false).when(service.mStackSupervisor).checkStartAnyActivityPermission(
                     any(), any(), any(), anyInt(), anyInt(), anyInt(), any(),
                     anyBoolean(), anyBoolean(), any(), any(), any());
@@ -448,7 +446,7 @@
         final int result = starter.setReason("testSplitScreenDeliverToTop").execute();
 
         // Ensure result is delivering intent to top.
-        assertEquals(result, START_DELIVERED_TO_TOP);
+        assertEquals(START_DELIVERED_TO_TOP, result);
     }
 
     /**
@@ -480,7 +478,7 @@
         final int result = starter.setReason("testSplitScreenMoveToFront").execute();
 
         // Ensure result is moving task to front.
-        assertEquals(result, START_TASK_TO_FRONT);
+        assertEquals(START_TASK_TO_FRONT, result);
     }
 
     /**
@@ -506,7 +504,7 @@
     private void assertNoTasks(ActivityDisplay display) {
         for (int i = display.getChildCount() - 1; i >= 0; --i) {
             final ActivityStack stack = display.getChildAt(i);
-            assertTrue(stack.getAllTasks().isEmpty());
+            assertThat(stack.getAllTasks()).isEmpty();
         }
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/am/ActivityTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
similarity index 93%
rename from services/tests/servicestests/src/com/android/server/am/ActivityTestsBase.java
rename to services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
index 57960ef..9d28c57 100644
--- a/services/tests/servicestests/src/com/android/server/am/ActivityTestsBase.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
@@ -24,8 +24,10 @@
 import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.DisplayAdjustments.DEFAULT_DISPLAY_ADJUSTMENTS;
 
-import static com.android.server.am.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
-import static com.android.server.am.ActivityStackSupervisor.ON_TOP;
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
+
+import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING;
+import static com.android.server.wm.ActivityStackSupervisor.ON_TOP;
 
 import static org.mockito.Mockito.any;
 import static org.mockito.Mockito.anyBoolean;
@@ -60,27 +62,17 @@
 import android.view.Display;
 import android.view.DisplayInfo;
 
-import androidx.test.InstrumentationRegistry;
-
 import com.android.internal.app.IVoiceInteractor;
 import com.android.server.AppOpsService;
 import com.android.server.AttributeCache;
 import com.android.server.ServiceThread;
+import com.android.server.am.ActivityManagerService;
 import com.android.server.uri.UriGrantsManagerInternal;
-import com.android.server.wm.ActivityTaskManagerInternal;
-import com.android.server.wm.AppWindowContainerController;
-import com.android.server.wm.DisplayWindowController;
-import com.android.server.wm.PinnedStackWindowController;
-import com.android.server.wm.RootWindowContainerController;
-import com.android.server.wm.StackWindowController;
-import com.android.server.wm.TaskWindowContainerController;
-import com.android.server.wm.WindowManagerService;
-import com.android.server.wm.WindowTestUtils;
 
 import org.junit.After;
 import org.junit.Before;
+import org.junit.BeforeClass;
 import org.junit.Rule;
-import org.mockito.MockitoAnnotations;
 import org.mockito.invocation.InvocationOnMock;
 
 import java.io.File;
@@ -89,16 +81,14 @@
 /**
  * A base class to handle common operations in activity related unit tests.
  */
-public class ActivityTestsBase {
-    private static boolean sOneTimeSetupDone = false;
-
+class ActivityTestsBase {
     private static int sNextDisplayId = DEFAULT_DISPLAY + 1;
 
     @Rule
     public final DexmakerShareClassLoaderRule mDexmakerShareClassLoaderRule =
             new DexmakerShareClassLoaderRule();
 
-    private final Context mContext = InstrumentationRegistry.getContext();
+    final Context mContext = getInstrumentation().getTargetContext();
     final TestInjector mTestInjector = new TestInjector();
 
     ActivityTaskManagerService mService;
@@ -110,22 +100,22 @@
     // Default base activity name
     private static final String DEFAULT_COMPONENT_CLASS_NAME = ".BarActivity";
 
+    @BeforeClass
+    public static void setUpOnceBase() {
+        AttributeCache.init(getInstrumentation().getTargetContext());
+    }
+
     @Before
-    public void setUp() throws Exception {
-        if (!sOneTimeSetupDone) {
-            sOneTimeSetupDone = true;
-            MockitoAnnotations.initMocks(this);
-            AttributeCache.init(mContext);
-        }
+    public void setUpBase() {
         mTestInjector.setUp();
     }
 
     @After
-    public void tearDown() {
+    public void tearDownBase() {
         mTestInjector.tearDown();
     }
 
-    protected ActivityTaskManagerService createActivityTaskManagerService() {
+    ActivityTaskManagerService createActivityTaskManagerService() {
         final TestActivityTaskManagerService atm =
                 spy(new TestActivityTaskManagerService(mContext));
         setupActivityManagerService(atm);
@@ -396,10 +386,10 @@
         }
 
         private static class TestTaskRecord extends TaskRecord {
-            TestTaskRecord(ActivityTaskManagerService service, int _taskId, ActivityInfo info,
-                       Intent _intent, IVoiceInteractionSession _voiceSession,
-                       IVoiceInteractor _voiceInteractor) {
-                super(service, _taskId, info, _intent, _voiceSession, _voiceInteractor);
+            TestTaskRecord(ActivityTaskManagerService service, int taskId, ActivityInfo info,
+                       Intent intent, IVoiceInteractionSession voiceSession,
+                       IVoiceInteractor voiceInteractor) {
+                super(service, taskId, info, intent, voiceSession, voiceInteractor);
             }
 
             @Override
@@ -451,7 +441,7 @@
         }
 
         @Override
-        final protected ActivityStackSupervisor createStackSupervisor() {
+        protected final ActivityStackSupervisor createStackSupervisor() {
             if (mTestStackSupervisor == null) {
                 final ActivityStackSupervisor supervisor = spy(createTestSupervisor());
                 final KeyguardController keyguardController = mock(KeyguardController.class);
@@ -486,10 +476,13 @@
             return mInternal;
         }
 
+        @Override
         PackageManagerInternal getPackageManagerInternalLocked() {
             if (mPmInternal == null) {
                 mPmInternal = mock(PackageManagerInternal.class);
-                doReturn(false).when(mPmInternal).isPermissionsReviewRequired(anyString(), anyInt());
+                doReturn(false)
+                        .when(mPmInternal)
+                        .isPermissionsReviewRequired(anyString(), anyInt());
             }
             return mPmInternal;
         }
@@ -500,7 +493,7 @@
 
         @Override
         public Context getContext() {
-            return InstrumentationRegistry.getContext();
+            return getInstrumentation().getTargetContext();
         }
 
         @Override
@@ -611,6 +604,7 @@
             mSupervisor = supervisor;
         }
 
+        @SuppressWarnings("TypeParameterUnusedInFormals")
         @Override
         <T extends ActivityStack> T createStackUnchecked(int windowingMode, int activityType,
                 int stackId, boolean onTop) {
@@ -798,6 +792,7 @@
             return this;
         }
 
+        @SuppressWarnings("TypeParameterUnusedInFormals")
         <T extends ActivityStack> T build() {
             final int stackId = mStackId >= 0 ? mStackId : mDisplay.getNextStackId();
             if (mWindowingMode == WINDOWING_MODE_PINNED) {
diff --git a/services/tests/servicestests/src/com/android/server/am/AssistDataRequesterTest.java b/services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java
similarity index 82%
rename from services/tests/servicestests/src/com/android/server/am/AssistDataRequesterTest.java
rename to services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java
index 1b823ff..c6c1c52 100644
--- a/services/tests/servicestests/src/com/android/server/am/AssistDataRequesterTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/AssistDataRequesterTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -11,10 +11,10 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.AppOpsManager.MODE_ALLOWED;
 import static android.app.AppOpsManager.MODE_ERRORED;
@@ -22,6 +22,9 @@
 import static android.app.AppOpsManager.OP_ASSIST_STRUCTURE;
 import static android.graphics.Bitmap.Config.ARGB_8888;
 
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
@@ -45,16 +48,14 @@
 import android.util.Log;
 import android.view.IWindowManager;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.FlakyTest;
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
+import com.android.server.am.AssistDataRequester;
 import com.android.server.am.AssistDataRequester.AssistDataRequesterCallbacks;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -65,11 +66,11 @@
  * Note: Currently, we only support fetching the screenshot for the current application, so the
  * screenshot checks are hardcoded accordingly.
  *
- * runtest --path frameworks/base/services/tests/servicestests/src/com/android/server/am/AssistDataRequesterTest.java
+ * Build/Install/Run:
+ *  atest WmTests:AssistDataRequesterTest
  */
 @MediumTest
 @FlakyTest(bugId = 113616538)
-@RunWith(AndroidJUnit4.class)
 public class AssistDataRequesterTest extends ActivityTestsBase {
 
     private static final String TAG = AssistDataRequesterTest.class.getSimpleName();
@@ -105,14 +106,11 @@
     private CountDownLatch mGate;
 
     @Before
-    @Override
     public void setUp() throws Exception {
-        super.setUp();
         mAm = mock(IActivityManager.class);
         mAtm = mock(IActivityTaskManager.class);
         mWm = mock(IWindowManager.class);
         mAppOpsManager = mock(AppOpsManager.class);
-        mContext =  InstrumentationRegistry.getContext();
         mHandler = new Handler(Looper.getMainLooper());
         mCallbacksLock = new Object();
         mCallbacks = new Callbacks();
@@ -190,35 +188,35 @@
         setupMocks(CURRENT_ACTIVITY_ASSIST_ALLOWED, CALLER_ASSIST_STRUCTURE_ALLOWED,
                 CALLER_ASSIST_SCREENSHOT_ALLOWED);
 
-        mCallbacks.canHandleReceivedData = false;
+        mCallbacks.mCanHandleReceivedData = false;
         mDataRequester.requestAssistData(createActivityList(5), FETCH_DATA, FETCH_SCREENSHOTS,
                 ALLOW_FETCH_DATA, ALLOW_FETCH_SCREENSHOTS, TEST_UID, TEST_PACKAGE);
-        assertTrue(mDataRequester.getPendingDataCount() == 5);
-        assertTrue(mDataRequester.getPendingScreenshotCount() == 1);
+        assertEquals(5, mDataRequester.getPendingDataCount());
+        assertEquals(1, mDataRequester.getPendingScreenshotCount());
         mGate.countDown();
         waitForIdle(mHandler);
 
         // Callbacks still not ready to receive, but all pending data is received
-        assertTrue(mDataRequester.getPendingDataCount() == 0);
-        assertTrue(mDataRequester.getPendingScreenshotCount() == 0);
-        assertTrue(mCallbacks.receivedData.isEmpty());
-        assertTrue(mCallbacks.receivedScreenshots.isEmpty());
-        assertFalse(mCallbacks.requestCompleted);
+        assertEquals(0, mDataRequester.getPendingDataCount());
+        assertEquals(0, mDataRequester.getPendingScreenshotCount());
+        assertThat(mCallbacks.mReceivedData).isEmpty();
+        assertThat(mCallbacks.mReceivedScreenshots).isEmpty();
+        assertFalse(mCallbacks.mRequestCompleted);
 
-        mCallbacks.canHandleReceivedData = true;
+        mCallbacks.mCanHandleReceivedData = true;
         mDataRequester.processPendingAssistData();
         // Since we are posting the callback for the request-complete, flush the handler as well
         mGate.countDown();
         waitForIdle(mHandler);
-        assertTrue(mCallbacks.receivedData.size() == 5);
-        assertTrue(mCallbacks.receivedScreenshots.size() == 1);
-        assertTrue(mCallbacks.requestCompleted);
+        assertEquals(5, mCallbacks.mReceivedData.size());
+        assertEquals(1, mCallbacks.mReceivedScreenshots.size());
+        assertTrue(mCallbacks.mRequestCompleted);
 
         // Clear the state and ensure that we only process pending data once
         mCallbacks.reset();
         mDataRequester.processPendingAssistData();
-        assertTrue(mCallbacks.receivedData.isEmpty());
-        assertTrue(mCallbacks.receivedScreenshots.isEmpty());
+        assertThat(mCallbacks.mReceivedData).isEmpty();
+        assertThat(mCallbacks.mReceivedScreenshots).isEmpty();
     }
 
     @Test
@@ -281,13 +279,13 @@
         setupMocks(CURRENT_ACTIVITY_ASSIST_ALLOWED, !CALLER_ASSIST_STRUCTURE_ALLOWED,
                 !CALLER_ASSIST_SCREENSHOT_ALLOWED);
 
-        mCallbacks.canHandleReceivedData = false;
+        mCallbacks.mCanHandleReceivedData = false;
         mDataRequester.requestAssistData(createActivityList(5), FETCH_DATA, FETCH_SCREENSHOTS,
                 ALLOW_FETCH_DATA, ALLOW_FETCH_SCREENSHOTS, TEST_UID, TEST_PACKAGE);
         mGate.countDown();
         waitForIdle(mHandler);
-        assertTrue(mCallbacks.receivedData.isEmpty());
-        assertTrue(mCallbacks.receivedScreenshots.isEmpty());
+        assertThat(mCallbacks.mReceivedData).isEmpty();
+        assertThat(mCallbacks.mReceivedScreenshots).isEmpty();
     }
 
     @Test
@@ -302,22 +300,22 @@
 
     private void assertReceivedDataCount(int numPendingData, int numReceivedData,
             int numPendingScreenshots, int numReceivedScreenshots) throws Exception {
-        assertTrue("Expected " + numPendingData + " pending data, got "
+        assertEquals("Expected " + numPendingData + " pending data, got "
                         + mDataRequester.getPendingDataCount(),
-                mDataRequester.getPendingDataCount() == numPendingData);
-        assertTrue("Expected " + numPendingScreenshots + " pending screenshots, got "
+                numPendingData, mDataRequester.getPendingDataCount());
+        assertEquals("Expected " + numPendingScreenshots + " pending screenshots, got "
                         + mDataRequester.getPendingScreenshotCount(),
-                mDataRequester.getPendingScreenshotCount() == numPendingScreenshots);
-        assertFalse("Expected request NOT completed", mCallbacks.requestCompleted);
+                numPendingScreenshots, mDataRequester.getPendingScreenshotCount());
+        assertFalse("Expected request NOT completed", mCallbacks.mRequestCompleted);
         mGate.countDown();
         waitForIdle(mHandler);
-        assertTrue("Expected " + numReceivedData + " data, received "
-                        + mCallbacks.receivedData.size(),
-                mCallbacks.receivedData.size() == numReceivedData);
-        assertTrue("Expected " + numReceivedScreenshots + " screenshots, received "
-                        + mCallbacks.receivedScreenshots.size(),
-                mCallbacks.receivedScreenshots.size() == numReceivedScreenshots);
-        assertTrue("Expected request completed", mCallbacks.requestCompleted);
+        assertEquals("Expected " + numReceivedData + " data, received "
+                        + mCallbacks.mReceivedData.size(),
+                numReceivedData, mCallbacks.mReceivedData.size());
+        assertEquals("Expected " + numReceivedScreenshots + " screenshots, received "
+                        + mCallbacks.mReceivedScreenshots.size(),
+                numReceivedScreenshots, mCallbacks.mReceivedScreenshots.size());
+        assertTrue("Expected request completed", mCallbacks.mRequestCompleted);
     }
 
     private List<IBinder> createActivityList(int size) {
@@ -339,30 +337,30 @@
 
     private class Callbacks implements AssistDataRequesterCallbacks {
 
-        boolean canHandleReceivedData = true;
-        boolean requestCompleted = false;
-        ArrayList<Bundle> receivedData = new ArrayList<>();
-        ArrayList<Bitmap> receivedScreenshots = new ArrayList<>();
+        public boolean mCanHandleReceivedData = true;
+        public boolean mRequestCompleted = false;
+        public final ArrayList<Bundle> mReceivedData = new ArrayList<>();
+        public final ArrayList<Bitmap> mReceivedScreenshots = new ArrayList<>();
 
         void reset() {
-            canHandleReceivedData = true;
-            receivedData.clear();
-            receivedScreenshots.clear();
+            mCanHandleReceivedData = true;
+            mReceivedData.clear();
+            mReceivedScreenshots.clear();
         }
 
         @Override
         public boolean canHandleReceivedAssistDataLocked() {
-            return canHandleReceivedData;
+            return mCanHandleReceivedData;
         }
 
         @Override
         public void onAssistDataReceivedLocked(Bundle data, int activityIndex, int activityCount) {
-            receivedData.add(data);
+            mReceivedData.add(data);
         }
 
         @Override
         public void onAssistScreenshotReceivedLocked(Bitmap screenshot) {
-            receivedScreenshots.add(screenshot);
+            mReceivedScreenshots.add(screenshot);
         }
 
         @Override
@@ -370,7 +368,7 @@
             mHandler.post(() -> {
                 try {
                     mGate.await(10, TimeUnit.SECONDS);
-                    requestCompleted = true;
+                    mRequestCompleted = true;
                 } catch (InterruptedException e) {
                     Log.e(TAG, "Failed to wait", e);
                 }
diff --git a/services/tests/servicestests/src/com/android/server/am/ClientLifecycleManagerTests.java b/services/tests/wmtests/src/com/android/server/wm/ClientLifecycleManagerTests.java
similarity index 64%
rename from services/tests/servicestests/src/com/android/server/am/ClientLifecycleManagerTests.java
rename to services/tests/wmtests/src/com/android/server/wm/ClientLifecycleManagerTests.java
index b4ad183..f1d840d 100644
--- a/services/tests/servicestests/src/com/android/server/am/ClientLifecycleManagerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ClientLifecycleManagerTests.java
@@ -1,4 +1,20 @@
-package com.android.server.am;
+/*
+ * Copyright (C) 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License
+ */
+
+package com.android.server.wm;
 
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
@@ -11,12 +27,13 @@
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
-@RunWith(AndroidJUnit4.class)
+/**
+ * Build/Install/Run:
+ *  atest WmTests:ClientLifecycleManagerTests
+ */
 @SmallTest
 @Presubmit
 public class ClientLifecycleManagerTests {
diff --git a/services/tests/servicestests/src/com/android/server/wm/ConfigurationContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/ConfigurationContainerTests.java
similarity index 94%
rename from services/tests/servicestests/src/com/android/server/wm/ConfigurationContainerTests.java
rename to services/tests/wmtests/src/com/android/server/wm/ConfigurationContainerTests.java
index 2b8214d..82a200b 100644
--- a/services/tests/servicestests/src/com/android/server/wm/ConfigurationContainerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ConfigurationContainerTests.java
@@ -11,13 +11,12 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
 package com.android.server.wm;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
@@ -36,10 +35,8 @@
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -48,15 +45,14 @@
  * Test class for {@link ConfigurationContainer}.
  *
  * Build/Install/Run:
- *  bit FrameworksServicesTests:com.android.server.wm.ConfigurationContainerTests
+ *  atest WmTests:ConfigurationContainerTests
  */
 @SmallTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class ConfigurationContainerTests {
 
     @Test
-    public void testConfigurationInit() throws Exception {
+    public void testConfigurationInit() {
         // Check root container initial config.
         final TestConfigurationContainer root = new TestConfigurationContainer();
         assertEquals(EMPTY, root.getOverrideConfiguration());
@@ -93,7 +89,7 @@
     }
 
     @Test
-    public void testConfigurationChangeOnAddRemove() throws Exception {
+    public void testConfigurationChangeOnAddRemove() {
         // Init root's config.
         final TestConfigurationContainer root = new TestConfigurationContainer();
         final Configuration rootOverrideConfig = new Configuration();
@@ -135,7 +131,7 @@
     }
 
     @Test
-    public void testConfigurationChangePropagation() throws Exception {
+    public void testConfigurationChangePropagation() {
         // Builds 3-level vertical hierarchy with one configuration container on each level.
         // In addition to different overrides on each level, everyone in hierarchy will have one
         // common overridden value - orientation;
@@ -212,7 +208,7 @@
     }
 
     @Test
-    public void testSetWindowingMode() throws Exception {
+    public void testSetWindowingMode() {
         final TestConfigurationContainer root = new TestConfigurationContainer();
         root.setWindowingMode(WINDOWING_MODE_UNDEFINED);
         final TestConfigurationContainer child = root.addChild();
@@ -226,7 +222,7 @@
     }
 
     @Test
-    public void testSetActivityType() throws Exception {
+    public void testSetActivityType() {
         final TestConfigurationContainer root = new TestConfigurationContainer();
         root.setActivityType(ACTIVITY_TYPE_UNDEFINED);
         final TestConfigurationContainer child = root.addChild();
@@ -272,7 +268,7 @@
     }
 
     @Test
-    public void testRegisterConfigurationChangeListener() throws Exception {
+    public void testRegisterConfigurationChangeListener() {
         final TestConfigurationContainer container = new TestConfigurationContainer();
         final TestConfigurationChangeListener listener = new TestConfigurationChangeListener();
         final Configuration config = new Configuration();
@@ -328,10 +324,11 @@
         }
     }
 
-    private class TestConfigurationChangeListener implements ConfigurationContainerListener {
+    private static class TestConfigurationChangeListener implements ConfigurationContainerListener {
 
         final Configuration mOverrideConfiguration = new Configuration();
 
+        @Override
         public void onOverrideConfigurationChanged(Configuration overrideConfiguration) {
             mOverrideConfiguration.setTo(overrideConfiguration);
         }
diff --git a/services/tests/wmtests/src/com/android/server/wm/DummyWmTests.java b/services/tests/wmtests/src/com/android/server/wm/DummyWmTests.java
deleted file mode 100644
index aecb278..0000000
--- a/services/tests/wmtests/src/com/android/server/wm/DummyWmTests.java
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (C) 2018 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package com.android.server.wm;
-
-import android.platform.test.annotations.Presubmit;
-
-import org.junit.Test;
-
-import androidx.test.filters.FlakyTest;
-
-/**
- * Dummy test for com.android.server.wm
- * TODO(b/113800711): Remove this class once the actual tests are moved from servicestests.
- */
-public class DummyWmTests {
-
-    @Presubmit
-    @Test
-    public void preSubmitTest() {}
-
-    @FlakyTest
-    @Presubmit
-    @Test
-    public void flakyPreSubmitTest() {}
-
-    @Test
-    public void postSubmitTest() {}
-
-    @FlakyTest
-    @Test
-    public void flakyPostSubmitTest() {}
-}
diff --git a/services/tests/servicestests/src/com/android/server/am/LaunchParamsControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java
similarity index 90%
rename from services/tests/servicestests/src/com/android/server/am/LaunchParamsControllerTests.java
rename to services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java
index 2fb10e1..40c20a4 100644
--- a/services/tests/servicestests/src/com/android/server/am/LaunchParamsControllerTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LaunchParamsControllerTests.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,15 +14,15 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
 import static android.view.Display.DEFAULT_DISPLAY;
 import static android.view.Display.INVALID_DISPLAY;
 
-import static com.android.server.am.LaunchParamsController.LaunchParamsModifier.RESULT_CONTINUE;
-import static com.android.server.am.LaunchParamsController.LaunchParamsModifier.RESULT_DONE;
-import static com.android.server.am.LaunchParamsController.LaunchParamsModifier.RESULT_SKIP;
+import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_CONTINUE;
+import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_DONE;
+import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_SKIP;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotEquals;
@@ -41,32 +41,26 @@
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
-import com.android.server.am.LaunchParamsController.LaunchParams;
-import com.android.server.am.LaunchParamsController.LaunchParamsModifier;
+import com.android.server.wm.LaunchParamsController.LaunchParams;
+import com.android.server.wm.LaunchParamsController.LaunchParamsModifier;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 /**
  * Tests for exercising {@link LaunchParamsController}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:LaunchParamsControllerTests
+ *  atest WmTests:LaunchParamsControllerTests
  */
 @MediumTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class LaunchParamsControllerTests extends ActivityTestsBase {
-    private ActivityTaskManagerService mService;
     private LaunchParamsController mController;
 
     @Before
-    @Override
     public void setUp() throws Exception {
-        super.setUp();
         mService = createActivityTaskManagerService();
         mController = new LaunchParamsController(mService);
     }
@@ -181,8 +175,7 @@
         mController.registerModifier(positioner1);
         mController.registerModifier(positioner2);
 
-        final LaunchParams
-                result = new LaunchParams();
+        final LaunchParams result = new LaunchParams();
 
         mController.calculate(null /*task*/, null /*layout*/, null /*activity*/, null /*source*/,
                 null /*options*/, result);
@@ -253,19 +246,18 @@
         mController.registerModifier(positioner);
 
         final int beforeWindowMode = task.getStack().getWindowingMode();
-        assertNotEquals(beforeWindowMode, windowingMode);
+        assertNotEquals(windowingMode, beforeWindowMode);
 
         mController.layoutTask(task, null /* windowLayout */);
 
         final int afterWindowMode = task.getStack().getWindowingMode();
-        assertEquals(afterWindowMode, windowingMode);
+        assertEquals(windowingMode, afterWindowMode);
     }
 
-    public static class InstrumentedPositioner implements
-            LaunchParamsModifier {
+    public static class InstrumentedPositioner implements LaunchParamsModifier {
 
-        final private int mReturnVal;
-        final private LaunchParams mParams;
+        private final int mReturnVal;
+        private final LaunchParams mParams;
 
         InstrumentedPositioner(int returnVal, LaunchParams params) {
             mReturnVal = returnVal;
diff --git a/services/tests/servicestests/src/com/android/server/am/LockTaskControllerTest.java b/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
similarity index 95%
rename from services/tests/servicestests/src/com/android/server/am/LockTaskControllerTest.java
rename to services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
index 863a0d8..6b613ed 100644
--- a/services/tests/servicestests/src/com/android/server/am/LockTaskControllerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/LockTaskControllerTest.java
@@ -1,20 +1,20 @@
 /*
- * Copyright 2017, The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityManager.LOCK_TASK_MODE_LOCKED;
 import static android.app.ActivityManager.LOCK_TASK_MODE_NONE;
@@ -32,12 +32,25 @@
 import static android.os.Process.SYSTEM_UID;
 import static android.telecom.TelecomManager.EMERGENCY_DIALER_COMPONENT;
 
-import static com.android.server.am.LockTaskController.STATUS_BAR_MASK_LOCKED;
-import static com.android.server.am.LockTaskController.STATUS_BAR_MASK_PINNED;
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
-import static org.junit.Assert.*;
-import static org.mockito.ArgumentMatchers.*;
-import static org.mockito.Mockito.*;
+import static com.android.server.wm.LockTaskController.STATUS_BAR_MASK_LOCKED;
+import static com.android.server.wm.LockTaskController.STATUS_BAR_MASK_PINNED;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import android.app.StatusBarManager;
 import android.app.admin.DevicePolicyManager;
@@ -56,7 +69,6 @@
 import android.testing.DexmakerShareClassLoaderRule;
 import android.util.Pair;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.SmallTest;
 
 import com.android.internal.statusbar.IStatusBarService;
@@ -77,10 +89,10 @@
  * Unit tests for {@link LockTaskController}.
  *
  * Build/Install/Run:
- *  bit FrameworksServicesTests:com.android.server.am.LockTaskControllerTest
+ *  atest WmTests:LockTaskControllerTest
  */
-@Presubmit
 @SmallTest
+@Presubmit
 public class LockTaskControllerTest {
     private static final String TEST_PACKAGE_NAME = "com.test.package";
     private static final String TEST_PACKAGE_NAME_2 = "com.test.package2";
@@ -109,7 +121,7 @@
     public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);
 
-        mContext = InstrumentationRegistry.getTargetContext();
+        mContext = getInstrumentation().getTargetContext();
         mLockToAppSetting = Settings.Secure.getString(mContext.getContentResolver(),
                 Settings.Secure.LOCK_TO_APP_EXIT_LOCKED);
 
@@ -183,7 +195,7 @@
     }
 
     @Test
-    public void testStartLockTaskMode_pinningRequest() throws Exception {
+    public void testStartLockTaskMode_pinningRequest() {
         // GIVEN a task record that is not whitelisted, i.e. with pinned auth
         TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_PINNABLE);
 
@@ -214,7 +226,7 @@
     }
 
     @Test
-    public void testLockTaskViolation() throws Exception {
+    public void testLockTaskViolation() {
         // GIVEN one task record with whitelisted auth that is in lock task mode
         TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED);
         mLockTaskController.startLockTaskMode(tr, false, TEST_UID);
@@ -240,7 +252,7 @@
     }
 
     @Test
-    public void testLockTaskViolation_emergencyCall() throws Exception {
+    public void testLockTaskViolation_emergencyCall() {
         // GIVEN one task record with whitelisted auth that is in lock task mode
         TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED);
         mLockTaskController.startLockTaskMode(tr, false, TEST_UID);
@@ -289,7 +301,7 @@
     }
 
     @Test(expected = SecurityException.class)
-    public void testStopLockTaskMode_differentCaller() throws Exception {
+    public void testStopLockTaskMode_differentCaller() {
         // GIVEN one task record with whitelisted auth that is in lock task mode
         TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED);
         mLockTaskController.startLockTaskMode(tr, false, TEST_UID);
@@ -301,7 +313,7 @@
     }
 
     @Test
-    public void testStopLockTaskMode_systemCaller() throws Exception {
+    public void testStopLockTaskMode_systemCaller() {
         // GIVEN one task record with whitelisted auth that is in lock task mode
         TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED);
         mLockTaskController.startLockTaskMode(tr, false, TEST_UID);
@@ -404,7 +416,7 @@
     }
 
     @Test
-    public void testUpdateLockTaskPackages() throws Exception {
+    public void testUpdateLockTaskPackages() {
         String[] whitelist1 = {TEST_PACKAGE_NAME, TEST_PACKAGE_NAME_2};
         String[] whitelist2 = {TEST_PACKAGE_NAME};
 
@@ -541,7 +553,7 @@
     }
 
     @Test
-    public void testUpdateLockTaskFeatures_keyguard() throws Exception {
+    public void testUpdateLockTaskFeatures_keyguard() {
         // GIVEN a locked task
         TaskRecord tr = getTaskRecord(TaskRecord.LOCK_TASK_AUTH_WHITELISTED);
         mLockTaskController.startLockTaskMode(tr, false, TEST_UID);
diff --git a/services/tests/servicestests/src/com/android/server/am/PendingRemoteAnimationRegistryTest.java b/services/tests/wmtests/src/com/android/server/wm/PendingRemoteAnimationRegistryTest.java
similarity index 92%
rename from services/tests/servicestests/src/com/android/server/am/PendingRemoteAnimationRegistryTest.java
rename to services/tests/wmtests/src/com/android/server/wm/PendingRemoteAnimationRegistryTest.java
index 4beebc4..efd7d25 100644
--- a/services/tests/servicestests/src/com/android/server/am/PendingRemoteAnimationRegistryTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/PendingRemoteAnimationRegistryTest.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
@@ -26,35 +26,31 @@
 
 import androidx.test.filters.FlakyTest;
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import com.android.server.testutils.OffsettableClock;
 import com.android.server.testutils.TestHandler;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
 /**
- * atest PendingRemoteAnimationRegistryTest
+ * Build/Install/Run:
+ *  atest WmTests:PendingRemoteAnimationRegistryTest
  */
 @SmallTest
-@Presubmit
 @FlakyTest
-@RunWith(AndroidJUnit4.class)
+@Presubmit
 public class PendingRemoteAnimationRegistryTest extends ActivityTestsBase {
 
     @Mock RemoteAnimationAdapter mAdapter;
     private PendingRemoteAnimationRegistry mRegistry;
     private final OffsettableClock mClock = new OffsettableClock.Stopped();
     private TestHandler mHandler;
-    private ActivityTaskManagerService mService;
 
     @Before
     public void setUp() throws Exception {
-        super.setUp();
         MockitoAnnotations.initMocks(this);
         mService = createActivityTaskManagerService();
         mService.mH.runWithScissors(() -> {
diff --git a/services/tests/servicestests/src/com/android/server/am/PersisterQueueTests.java b/services/tests/wmtests/src/com/android/server/wm/PersisterQueueTests.java
similarity index 93%
rename from services/tests/servicestests/src/com/android/server/am/PersisterQueueTests.java
rename to services/tests/wmtests/src/com/android/server/wm/PersisterQueueTests.java
index d7794b0..20150b4 100644
--- a/services/tests/servicestests/src/com/android/server/am/PersisterQueueTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/PersisterQueueTests.java
@@ -11,11 +11,12 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
+
+import static com.google.common.truth.Truth.assertWithMessage;
 
 import static junit.framework.Assert.assertNull;
 import static junit.framework.Assert.assertSame;
@@ -27,10 +28,12 @@
 import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
 
+import androidx.test.filters.FlakyTest;
+import androidx.test.filters.MediumTest;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -39,17 +42,13 @@
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.function.Predicate;
 
-import androidx.test.filters.FlakyTest;
-import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
-
 /**
- * atest PersisterQueueTests
+ * Build/Install/Run:
+ *  atest WmTests:PersisterQueueTests
  */
-@RunWith(AndroidJUnit4.class)
 @MediumTest
-@Presubmit
 @FlakyTest(detail = "Confirm stable in post-submit before removing")
+@Presubmit
 public class PersisterQueueTests implements PersisterQueue.Listener {
     private static final long INTER_WRITE_DELAY_MS = 50;
     private static final long PRE_TASK_DELAY_MS = 300;
@@ -63,7 +62,8 @@
     private volatile CountDownLatch mLatch;
     private List<Boolean> mProbablyDoneResults;
 
-    private PersisterQueue mTarget;
+    private final PersisterQueue mTarget =
+            new PersisterQueue(INTER_WRITE_DELAY_MS, PRE_TASK_DELAY_MS);
 
     @Before
     public void setUp() throws Exception {
@@ -71,7 +71,6 @@
         mProbablyDoneResults = new ArrayList<>();
         mSetUpLatch = new CountDownLatch(1);
 
-        mTarget = new PersisterQueue(INTER_WRITE_DELAY_MS, PRE_TASK_DELAY_MS);
         mTarget.addListener(this);
         mTarget.startPersisting();
 
@@ -82,10 +81,11 @@
     @After
     public void tearDown() throws Exception {
         mTarget.stopPersisting();
+        mTarget.removeListener(this);
     }
 
     @Test
-    public void testCallCallbackOnStartUp() throws Exception {
+    public void testCallCallbackOnStartUp() {
         // The onPreProcessItem() must be called on start up.
         assertEquals(1, mProbablyDoneResults.size());
         // The last one must be called with probably done being true.
@@ -197,7 +197,7 @@
     }
 
     @Test
-    public void testFindLastItemNotReturnDifferentType() throws Exception {
+    public void testFindLastItemNotReturnDifferentType() {
         synchronized (mTarget) {
             mTarget.addItem(new TestItem(), false);
             assertNull(mTarget.findLastItem(TEST_ITEM_PREDICATE, MatchingTestItem.class));
@@ -205,7 +205,7 @@
     }
 
     @Test
-    public void testFindLastItemNotReturnMismatchItem() throws Exception {
+    public void testFindLastItemNotReturnMismatchItem() {
         synchronized (mTarget) {
             mTarget.addItem(new MatchingTestItem(false), false);
             assertNull(mTarget.findLastItem(TEST_ITEM_PREDICATE, MatchingTestItem.class));
@@ -213,7 +213,7 @@
     }
 
     @Test
-    public void testFindLastItemReturnMatchedItem() throws Exception {
+    public void testFindLastItemReturnMatchedItem() {
         synchronized (mTarget) {
             final MatchingTestItem item = new MatchingTestItem(true);
             mTarget.addItem(item, false);
@@ -267,8 +267,8 @@
         assertEquals("Flush should wait until all items are processed before return.",
                 2, mItemCount.get());
         final long processTime = SystemClock.uptimeMillis() - dispatchTime;
-        assertTrue("Flush should trigger immediate flush without delays. processTime: "
-                + processTime, processTime < TIMEOUT_ALLOWANCE);
+        assertWithMessage("Flush should trigger immediate flush without delays. processTime: "
+                + processTime).that(processTime).isLessThan(TIMEOUT_ALLOWANCE);
     }
 
     @Override
diff --git a/services/tests/servicestests/src/com/android/server/am/RecentTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
similarity index 70%
rename from services/tests/servicestests/src/com/android/server/am/RecentTasksTest.java
rename to services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
index 04fe787..26241d2 100644
--- a/services/tests/servicestests/src/com/android/server/am/RecentTasksTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -11,13 +11,12 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.ActivityTaskManager.SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT;
-import static android.app.WindowConfiguration.ACTIVITY_TYPE_ASSISTANT;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_HOME;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
@@ -30,6 +29,9 @@
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
 import static android.view.Display.DEFAULT_DISPLAY;
 
+import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.truth.Truth.assertWithMessage;
+
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
@@ -39,6 +41,8 @@
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.spy;
 
+import static java.lang.Integer.MAX_VALUE;
+
 import android.app.ActivityManager.RecentTaskInfo;
 import android.app.ActivityManager.RunningTaskInfo;
 import android.app.ActivityTaskManager;
@@ -58,44 +62,37 @@
 import android.util.MutableLong;
 import android.util.SparseBooleanArray;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
-import com.android.server.am.RecentTasks.Callbacks;
+import com.android.server.wm.RecentTasks.Callbacks;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import static java.lang.Integer.MAX_VALUE;
 
 import java.io.File;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Random;
 import java.util.Set;
 
 /**
- * atest FrameworksServicesTests:RecentTasksTest
+ * Build/Install/Run:
+ *  atest WmTests:RecentTasksTest
  */
 @MediumTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class RecentTasksTest extends ActivityTestsBase {
     private static final int TEST_USER_0_ID = 0;
     private static final int TEST_USER_1_ID = 10;
     private static final int TEST_QUIET_USER_ID = 20;
     private static final UserInfo DEFAULT_USER_INFO = new UserInfo();
     private static final UserInfo QUIET_USER_INFO = new UserInfo();
-    private static int LAST_TASK_ID = 1;
-    private static int LAST_STACK_ID = 1;
-    private static int INVALID_STACK_ID = 999;
+    private static int sLastTaskId = 1;
+    private static int sLastStackId = 1;
+    private static final int INVALID_STACK_ID = 999;
 
-    private Context mContext = InstrumentationRegistry.getContext();
-    private TestActivityTaskManagerService mService;
+    private TestActivityTaskManagerService mTestService;
     private ActivityDisplay mDisplay;
     private ActivityDisplay mOtherDisplay;
     private ActivityStack mStack;
@@ -110,19 +107,16 @@
     private CallbacksRecorder mCallbacksRecorder;
 
     @Before
-    @Override
     public void setUp() throws Exception {
-        super.setUp();
-
         mTaskPersister = new TestTaskPersister(mContext.getFilesDir());
-        mService = spy(new MyTestActivityTaskManagerService(mContext));
+        mTestService = spy(new MyTestActivityTaskManagerService(mContext));
         final TestActivityManagerService am = spy(new MyTestActivityManagerService());
-        setupActivityManagerService(am, mService);
-        mRecentTasks = (TestRecentTasks) mService.getRecentTasks();
+        setupActivityManagerService(am, mTestService);
+        mRecentTasks = (TestRecentTasks) mTestService.getRecentTasks();
         mRecentTasks.loadParametersFromResources(mContext.getResources());
-        mHomeStack = mService.mStackSupervisor.getDefaultDisplay().getOrCreateStack(
+        mHomeStack = mTestService.mStackSupervisor.getDefaultDisplay().getOrCreateStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */);
-        mStack = mService.mStackSupervisor.getDefaultDisplay().createStack(
+        mStack = mTestService.mStackSupervisor.getDefaultDisplay().createStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
         mCallbacksRecorder = new CallbacksRecorder();
         mRecentTasks.registerCallback(mCallbacksRecorder);
@@ -141,50 +135,50 @@
     }
 
     @Test
-    public void testCallbacks() throws Exception {
+    public void testCallbacks() {
         // Add some tasks
         mRecentTasks.add(mTasks.get(0));
         mRecentTasks.add(mTasks.get(1));
-        assertTrue(mCallbacksRecorder.added.contains(mTasks.get(0))
-                && mCallbacksRecorder.added.contains(mTasks.get(1)));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.isEmpty());
+        assertThat(mCallbacksRecorder.mAdded).contains(mTasks.get(0));
+        assertThat(mCallbacksRecorder.mAdded).contains(mTasks.get(1));
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).isEmpty();
         mCallbacksRecorder.clear();
 
         // Remove some tasks
         mRecentTasks.remove(mTasks.get(0));
         mRecentTasks.remove(mTasks.get(1));
-        assertTrue(mCallbacksRecorder.added.isEmpty());
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.contains(mTasks.get(0)));
-        assertTrue(mCallbacksRecorder.removed.contains(mTasks.get(1)));
+        assertThat(mCallbacksRecorder.mAdded).isEmpty();
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).contains(mTasks.get(0));
+        assertThat(mCallbacksRecorder.mRemoved).contains(mTasks.get(1));
         mCallbacksRecorder.clear();
 
         // Remove the callback, ensure we don't get any calls
         mRecentTasks.unregisterCallback(mCallbacksRecorder);
         mRecentTasks.add(mTasks.get(0));
         mRecentTasks.remove(mTasks.get(0));
-        assertTrue(mCallbacksRecorder.added.isEmpty());
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.isEmpty());
+        assertThat(mCallbacksRecorder.mAdded).isEmpty();
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).isEmpty();
     }
 
     @Test
-    public void testAddTasksNoMultiple_expectNoTrim() throws Exception {
+    public void testAddTasksNoMultiple_expectNoTrim() {
         // Add same non-multiple-task document tasks will remove the task (to re-add it) but not
         // trim it
         TaskRecord documentTask1 = createDocumentTask(".DocumentTask1");
         TaskRecord documentTask2 = createDocumentTask(".DocumentTask1");
         mRecentTasks.add(documentTask1);
         mRecentTasks.add(documentTask2);
-        assertTrue(mCallbacksRecorder.added.contains(documentTask1));
-        assertTrue(mCallbacksRecorder.added.contains(documentTask2));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.contains(documentTask1));
+        assertThat(mCallbacksRecorder.mAdded).contains(documentTask1);
+        assertThat(mCallbacksRecorder.mAdded).contains(documentTask2);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).contains(documentTask1);
     }
 
     @Test
-    public void testAddTasksMaxTaskRecents_expectNoTrim() throws Exception {
+    public void testAddTasksMaxTaskRecents_expectNoTrim() {
         // Add a task hitting max-recents for that app will remove the task (to add the next one)
         // but not trim it
         TaskRecord documentTask1 = createDocumentTask(".DocumentTask1");
@@ -193,27 +187,27 @@
         documentTask2.maxRecents = 1;
         mRecentTasks.add(documentTask1);
         mRecentTasks.add(documentTask2);
-        assertTrue(mCallbacksRecorder.added.contains(documentTask1));
-        assertTrue(mCallbacksRecorder.added.contains(documentTask2));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.contains(documentTask1));
+        assertThat(mCallbacksRecorder.mAdded).contains(documentTask1);
+        assertThat(mCallbacksRecorder.mAdded).contains(documentTask2);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).contains(documentTask1);
     }
 
     @Test
-    public void testAddTasksSameTask_expectNoTrim() throws Exception {
+    public void testAddTasksSameTask_expectNoTrim() {
         // Add a task that is already in the task list does not trigger any callbacks, it just
         // moves in the list
         TaskRecord documentTask1 = createDocumentTask(".DocumentTask1");
         mRecentTasks.add(documentTask1);
         mRecentTasks.add(documentTask1);
-        assertTrue(mCallbacksRecorder.added.size() == 1);
-        assertTrue(mCallbacksRecorder.added.contains(documentTask1));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.isEmpty());
+        assertThat(mCallbacksRecorder.mAdded).hasSize(1);
+        assertThat(mCallbacksRecorder.mAdded).contains(documentTask1);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).isEmpty();
     }
 
     @Test
-    public void testAddTasksMultipleDocumentTasks_expectNoTrim() throws Exception {
+    public void testAddTasksMultipleDocumentTasks_expectNoTrim() {
         // Add same multiple-task document tasks does not trim the first tasks
         TaskRecord documentTask1 = createDocumentTask(".DocumentTask1",
                 FLAG_ACTIVITY_MULTIPLE_TASK);
@@ -221,15 +215,15 @@
                 FLAG_ACTIVITY_MULTIPLE_TASK);
         mRecentTasks.add(documentTask1);
         mRecentTasks.add(documentTask2);
-        assertTrue(mCallbacksRecorder.added.size() == 2);
-        assertTrue(mCallbacksRecorder.added.contains(documentTask1));
-        assertTrue(mCallbacksRecorder.added.contains(documentTask2));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.isEmpty());
+        assertThat(mCallbacksRecorder.mAdded).hasSize(2);
+        assertThat(mCallbacksRecorder.mAdded).contains(documentTask1);
+        assertThat(mCallbacksRecorder.mAdded).contains(documentTask2);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).isEmpty();
     }
 
     @Test
-    public void testAddTasksMultipleTasks_expectRemovedNoTrim() throws Exception {
+    public void testAddTasksMultipleTasks_expectRemovedNoTrim() {
         // Add multiple same-affinity non-document tasks, ensure that it removes the other task,
         // but that it does not trim it
         TaskRecord task1 = createTaskBuilder(".Task1")
@@ -239,21 +233,21 @@
                 .setFlags(FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_MULTIPLE_TASK)
                 .build();
         mRecentTasks.add(task1);
-        assertTrue(mCallbacksRecorder.added.size() == 1);
-        assertTrue(mCallbacksRecorder.added.contains(task1));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.isEmpty());
+        assertThat(mCallbacksRecorder.mAdded).hasSize(1);
+        assertThat(mCallbacksRecorder.mAdded).contains(task1);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).isEmpty();
         mCallbacksRecorder.clear();
         mRecentTasks.add(task2);
-        assertTrue(mCallbacksRecorder.added.size() == 1);
-        assertTrue(mCallbacksRecorder.added.contains(task2));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.size() == 1);
-        assertTrue(mCallbacksRecorder.removed.contains(task1));
+        assertThat(mCallbacksRecorder.mAdded).hasSize(1);
+        assertThat(mCallbacksRecorder.mAdded).contains(task2);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).hasSize(1);
+        assertThat(mCallbacksRecorder.mRemoved).contains(task1);
     }
 
     @Test
-    public void testAddTasksDifferentStacks_expectNoRemove() throws Exception {
+    public void testAddTasksDifferentStacks_expectNoRemove() {
         // Adding the same task with different activity types should not trigger removal of the
         // other task
         TaskRecord task1 = createTaskBuilder(".Task1")
@@ -264,15 +258,15 @@
                 .setStack(mStack).build();
         mRecentTasks.add(task1);
         mRecentTasks.add(task2);
-        assertTrue(mCallbacksRecorder.added.size() == 2);
-        assertTrue(mCallbacksRecorder.added.contains(task1));
-        assertTrue(mCallbacksRecorder.added.contains(task2));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.isEmpty());
+        assertThat(mCallbacksRecorder.mAdded).hasSize(2);
+        assertThat(mCallbacksRecorder.mAdded).contains(task1);
+        assertThat(mCallbacksRecorder.mAdded).contains(task2);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).isEmpty();
     }
 
     @Test
-    public void testAddTaskCompatibleActivityType_expectRemove() throws Exception {
+    public void testAddTaskCompatibleActivityType_expectRemove() {
         // Test with undefined activity type since the type is not persisted by the task persister
         // and we want to ensure that a new task will match a restored task
         TaskRecord task1 = createTaskBuilder(".Task1")
@@ -280,7 +274,7 @@
                 .setStack(mStack)
                 .build();
         setTaskActivityType(task1, ACTIVITY_TYPE_UNDEFINED);
-        assertTrue(task1.getActivityType() == ACTIVITY_TYPE_UNDEFINED);
+        assertThat(task1.getActivityType()).isEqualTo(ACTIVITY_TYPE_UNDEFINED);
         mRecentTasks.add(task1);
         mCallbacksRecorder.clear();
 
@@ -288,24 +282,24 @@
                 .setFlags(FLAG_ACTIVITY_NEW_TASK)
                 .setStack(mStack)
                 .build();
-        assertTrue(task2.getActivityType() == ACTIVITY_TYPE_STANDARD);
+        assertEquals(ACTIVITY_TYPE_STANDARD, task2.getActivityType());
         mRecentTasks.add(task2);
-        assertTrue(mCallbacksRecorder.added.size() == 1);
-        assertTrue(mCallbacksRecorder.added.contains(task2));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.size() == 1);
-        assertTrue(mCallbacksRecorder.removed.contains(task1));
+        assertThat(mCallbacksRecorder.mAdded).hasSize(1);
+        assertThat(mCallbacksRecorder.mAdded).contains(task2);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).hasSize(1);
+        assertThat(mCallbacksRecorder.mRemoved).contains(task1);
     }
 
     @Test
-    public void testAddTaskCompatibleActivityTypeDifferentUser_expectNoRemove() throws Exception {
+    public void testAddTaskCompatibleActivityTypeDifferentUser_expectNoRemove() {
         TaskRecord task1 = createTaskBuilder(".Task1")
                 .setFlags(FLAG_ACTIVITY_NEW_TASK)
                 .setStack(mStack)
                 .setUserId(TEST_USER_0_ID)
                 .build();
         setTaskActivityType(task1, ACTIVITY_TYPE_UNDEFINED);
-        assertTrue(task1.getActivityType() == ACTIVITY_TYPE_UNDEFINED);
+        assertEquals(ACTIVITY_TYPE_UNDEFINED, task1.getActivityType());
         mRecentTasks.add(task1);
         mCallbacksRecorder.clear();
 
@@ -314,22 +308,22 @@
                 .setStack(mStack)
                 .setUserId(TEST_USER_1_ID)
                 .build();
-        assertTrue(task2.getActivityType() == ACTIVITY_TYPE_STANDARD);
+        assertEquals(ACTIVITY_TYPE_STANDARD, task2.getActivityType());
         mRecentTasks.add(task2);
-        assertTrue(mCallbacksRecorder.added.size() == 1);
-        assertTrue(mCallbacksRecorder.added.contains(task2));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.isEmpty());
+        assertThat(mCallbacksRecorder.mAdded).hasSize(1);
+        assertThat(mCallbacksRecorder.mAdded).contains(task2);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).isEmpty();
     }
 
     @Test
-    public void testAddTaskCompatibleWindowingMode_expectRemove() throws Exception {
+    public void testAddTaskCompatibleWindowingMode_expectRemove() {
         TaskRecord task1 = createTaskBuilder(".Task1")
                 .setFlags(FLAG_ACTIVITY_NEW_TASK)
                 .setStack(mStack)
                 .build();
         setTaskWindowingMode(task1, WINDOWING_MODE_UNDEFINED);
-        assertTrue(task1.getWindowingMode() == WINDOWING_MODE_UNDEFINED);
+        assertEquals(WINDOWING_MODE_UNDEFINED, task1.getWindowingMode());
         mRecentTasks.add(task1);
         mCallbacksRecorder.clear();
 
@@ -338,24 +332,24 @@
                 .setStack(mStack)
                 .build();
         setTaskWindowingMode(task2, WINDOWING_MODE_FULLSCREEN);
-        assertTrue(task2.getWindowingMode() == WINDOWING_MODE_FULLSCREEN);
+        assertEquals(WINDOWING_MODE_FULLSCREEN, task2.getWindowingMode());
         mRecentTasks.add(task2);
 
-        assertTrue(mCallbacksRecorder.added.size() == 1);
-        assertTrue(mCallbacksRecorder.added.contains(task2));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.size() == 1);
-        assertTrue(mCallbacksRecorder.removed.contains(task1));
+        assertThat(mCallbacksRecorder.mAdded).hasSize(1);
+        assertThat(mCallbacksRecorder.mAdded).contains(task2);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).hasSize(1);
+        assertThat(mCallbacksRecorder.mRemoved).contains(task1);
     }
 
     @Test
-    public void testAddTaskIncompatibleWindowingMode_expectNoRemove() throws Exception {
+    public void testAddTaskIncompatibleWindowingMode_expectNoRemove() {
         TaskRecord task1 = createTaskBuilder(".Task1")
                 .setFlags(FLAG_ACTIVITY_NEW_TASK)
                 .setStack(mStack)
                 .build();
         setTaskWindowingMode(task1, WINDOWING_MODE_FULLSCREEN);
-        assertTrue(task1.getWindowingMode() == WINDOWING_MODE_FULLSCREEN);
+        assertEquals(WINDOWING_MODE_FULLSCREEN, task1.getWindowingMode());
         mRecentTasks.add(task1);
 
         TaskRecord task2 = createTaskBuilder(".Task1")
@@ -363,41 +357,41 @@
                 .setStack(mStack)
                 .build();
         setTaskWindowingMode(task2, WINDOWING_MODE_PINNED);
-        assertTrue(task2.getWindowingMode() == WINDOWING_MODE_PINNED);
+        assertEquals(WINDOWING_MODE_PINNED, task2.getWindowingMode());
         mRecentTasks.add(task2);
 
-        assertTrue(mCallbacksRecorder.added.size() == 2);
-        assertTrue(mCallbacksRecorder.added.contains(task1));
-        assertTrue(mCallbacksRecorder.added.contains(task2));
-        assertTrue(mCallbacksRecorder.trimmed.isEmpty());
-        assertTrue(mCallbacksRecorder.removed.isEmpty());
+        assertThat(mCallbacksRecorder.mAdded).hasSize(2);
+        assertThat(mCallbacksRecorder.mAdded).contains(task1);
+        assertThat(mCallbacksRecorder.mAdded).contains(task2);
+        assertThat(mCallbacksRecorder.mTrimmed).isEmpty();
+        assertThat(mCallbacksRecorder.mRemoved).isEmpty();
     }
 
     @Test
-    public void testUsersTasks() throws Exception {
+    public void testUsersTasks() {
         mRecentTasks.setOnlyTestVisibleRange();
 
         // Setup some tasks for the users
-        mTaskPersister.userTaskIdsOverride = new SparseBooleanArray();
-        mTaskPersister.userTaskIdsOverride.put(1, true);
-        mTaskPersister.userTaskIdsOverride.put(2, true);
-        mTaskPersister.userTasksOverride = new ArrayList<>();
-        mTaskPersister.userTasksOverride.add(createTaskBuilder(".UserTask1").build());
-        mTaskPersister.userTasksOverride.add(createTaskBuilder(".UserTask2").build());
+        mTaskPersister.mUserTaskIdsOverride = new SparseBooleanArray();
+        mTaskPersister.mUserTaskIdsOverride.put(1, true);
+        mTaskPersister.mUserTaskIdsOverride.put(2, true);
+        mTaskPersister.mUserTasksOverride = new ArrayList<>();
+        mTaskPersister.mUserTasksOverride.add(createTaskBuilder(".UserTask1").build());
+        mTaskPersister.mUserTasksOverride.add(createTaskBuilder(".UserTask2").build());
 
         // Assert no user tasks are initially loaded
-        assertTrue(mRecentTasks.usersWithRecentsLoadedLocked().length == 0);
+        assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).hasLength(0);
 
         // Load user 0 tasks
         mRecentTasks.loadUserRecentsLocked(TEST_USER_0_ID);
-        assertTrue(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_0_ID));
+        assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList().contains(TEST_USER_0_ID);
         assertTrue(mRecentTasks.containsTaskId(1, TEST_USER_0_ID));
         assertTrue(mRecentTasks.containsTaskId(2, TEST_USER_0_ID));
 
         // Load user 1 tasks
         mRecentTasks.loadUserRecentsLocked(TEST_USER_1_ID);
-        assertTrue(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_0_ID));
-        assertTrue(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_1_ID));
+        assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList().contains(TEST_USER_0_ID);
+        assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList().contains(TEST_USER_1_ID);
         assertTrue(mRecentTasks.containsTaskId(1, TEST_USER_0_ID));
         assertTrue(mRecentTasks.containsTaskId(2, TEST_USER_0_ID));
         assertTrue(mRecentTasks.containsTaskId(1, TEST_USER_1_ID));
@@ -405,19 +399,22 @@
 
         // Unload user 1 tasks
         mRecentTasks.unloadUserDataFromMemoryLocked(TEST_USER_1_ID);
-        assertTrue(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_0_ID));
-        assertFalse(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_1_ID));
+        assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList().contains(TEST_USER_0_ID);
+        assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList()
+                .doesNotContain(TEST_USER_1_ID);
         assertTrue(mRecentTasks.containsTaskId(1, TEST_USER_0_ID));
         assertTrue(mRecentTasks.containsTaskId(2, TEST_USER_0_ID));
 
         // Unload user 0 tasks
         mRecentTasks.unloadUserDataFromMemoryLocked(TEST_USER_0_ID);
-        assertFalse(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_0_ID));
-        assertFalse(arrayContainsUser(mRecentTasks.usersWithRecentsLoadedLocked(), TEST_USER_1_ID));
+        assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList()
+                .doesNotContain(TEST_USER_0_ID);
+        assertThat(mRecentTasks.usersWithRecentsLoadedLocked()).asList()
+                .doesNotContain(TEST_USER_1_ID);
     }
 
     @Test
-    public void testOrderedIteration() throws Exception {
+    public void testOrderedIteration() {
         mRecentTasks.setOnlyTestVisibleRange();
         TaskRecord task1 = createTaskBuilder(".Task1").build();
         task1.lastActiveTime = new Random().nextInt();
@@ -436,13 +433,13 @@
         final ArrayList<TaskRecord> tasks = mRecentTasks.getRawTasks();
         for (int i = 0; i < tasks.size(); i++) {
             final TaskRecord task = tasks.get(i);
-            assertTrue(task.lastActiveTime >= prevLastActiveTime.value);
+            assertThat(prevLastActiveTime.value).isLessThan(task.lastActiveTime);
             prevLastActiveTime.value = task.lastActiveTime;
         }
     }
 
     @Test
-    public void testTrimToGlobalMaxNumRecents() throws Exception {
+    public void testTrimToGlobalMaxNumRecents() {
         mRecentTasks.setOnlyTestVisibleRange();
 
         // Limit the global maximum number of recent tasks to a fixed size
@@ -458,7 +455,7 @@
     }
 
     @Test
-    public void testTrimQuietProfileTasks() throws Exception {
+    public void testTrimQuietProfileTasks() {
         mRecentTasks.setOnlyTestVisibleRange();
         TaskRecord qt1 = createTaskBuilder(".QuietTask1").setUserId(TEST_QUIET_USER_ID).build();
         TaskRecord qt2 = createTaskBuilder(".QuietTask2").setUserId(TEST_QUIET_USER_ID).build();
@@ -473,7 +470,7 @@
     }
 
     @Test
-    public void testSessionDuration() throws Exception {
+    public void testSessionDuration() {
         mRecentTasks.setOnlyTestVisibleRange();
         mRecentTasks.setParameters(-1 /* min */, -1 /* max */, 50 /* ms */);
 
@@ -493,7 +490,7 @@
     }
 
     @Test
-    public void testVisibleTasks_excludedFromRecents() throws Exception {
+    public void testVisibleTasks_excludedFromRecents() {
         mRecentTasks.setOnlyTestVisibleRange();
         mRecentTasks.setParameters(-1 /* min */, 4 /* max */, -1 /* ms */);
 
@@ -515,7 +512,7 @@
     }
 
     @Test
-    public void testVisibleTasks_minNum() throws Exception {
+    public void testVisibleTasks_minNum() {
         mRecentTasks.setOnlyTestVisibleRange();
         mRecentTasks.setParameters(5 /* min */, -1 /* max */, 25 /* ms */);
 
@@ -536,7 +533,7 @@
     }
 
     @Test
-    public void testVisibleTasks_maxNum() throws Exception {
+    public void testVisibleTasks_maxNum() {
         mRecentTasks.setOnlyTestVisibleRange();
         mRecentTasks.setParameters(-1 /* min */, 3 /* max */, -1 /* ms */);
 
@@ -551,11 +548,11 @@
     }
 
     @Test
-    public void testBackStackTasks_expectNoTrim() throws Exception {
+    public void testBackStackTasks_expectNoTrim() {
         mRecentTasks.setParameters(-1 /* min */, 1 /* max */, -1 /* ms */);
 
         final MyTestActivityStackSupervisor supervisor =
-                (MyTestActivityStackSupervisor) mService.mStackSupervisor;
+                (MyTestActivityStackSupervisor) mTestService.mStackSupervisor;
         final ActivityStack homeStack = mDisplay.getHomeStack();
         final ActivityStack aboveHomeStack = new MyTestActivityStack(mDisplay, supervisor);
 
@@ -570,11 +567,11 @@
     }
 
     @Test
-    public void testBehindHomeStackTasks_expectTaskTrimmed() throws Exception {
+    public void testBehindHomeStackTasks_expectTaskTrimmed() {
         mRecentTasks.setParameters(-1 /* min */, 1 /* max */, -1 /* ms */);
 
         final MyTestActivityStackSupervisor supervisor =
-                (MyTestActivityStackSupervisor) mService.mStackSupervisor;
+                (MyTestActivityStackSupervisor) mTestService.mStackSupervisor;
         final ActivityStack behindHomeStack = new MyTestActivityStack(mDisplay, supervisor);
         final ActivityStack homeStack = mDisplay.getHomeStack();
         final ActivityStack aboveHomeStack = new MyTestActivityStack(mDisplay, supervisor);
@@ -592,11 +589,11 @@
     }
 
     @Test
-    public void testOtherDisplayTasks_expectNoTrim() throws Exception {
+    public void testOtherDisplayTasks_expectNoTrim() {
         mRecentTasks.setParameters(-1 /* min */, 1 /* max */, -1 /* ms */);
 
         final MyTestActivityStackSupervisor supervisor =
-                (MyTestActivityStackSupervisor) mService.mStackSupervisor;
+                (MyTestActivityStackSupervisor) mTestService.mStackSupervisor;
         final ActivityStack homeStack = mDisplay.getHomeStack();
         final ActivityStack otherDisplayStack = new MyTestActivityStack(mOtherDisplay, supervisor);
 
@@ -611,7 +608,7 @@
     }
 
     @Test
-    public void testRemovePackageByName() throws Exception {
+    public void testRemovePackageByName() {
         // Add a number of tasks with the same package name
         mRecentTasks.add(createTaskBuilder("com.android.pkg1", ".Task1").build());
         mRecentTasks.add(createTaskBuilder("com.android.pkg2", ".Task2").build());
@@ -628,7 +625,7 @@
     }
 
     @Test
-    public void testRemoveAllVisibleTasks() throws Exception {
+    public void testRemoveAllVisibleTasks() {
         mRecentTasks.setParameters(-1 /* min */, 3 /* max */, 100 /* ms */);
 
         // Create some set of tasks, some of which are visible and some are not
@@ -674,16 +671,16 @@
         mStack.remove();
 
         // The following APIs should not restore task from recents to the active list.
-        assertNotRestoreTask(() -> mService.setFocusedTask(taskId));
-        assertNotRestoreTask(() -> mService.startSystemLockTaskMode(taskId));
-        assertNotRestoreTask(() -> mService.cancelTaskWindowTransition(taskId));
+        assertNotRestoreTask(() -> mTestService.setFocusedTask(taskId));
+        assertNotRestoreTask(() -> mTestService.startSystemLockTaskMode(taskId));
+        assertNotRestoreTask(() -> mTestService.cancelTaskWindowTransition(taskId));
         assertNotRestoreTask(
-                () -> mService.resizeTask(taskId, null /* bounds */, 0 /* resizeMode */));
+                () -> mTestService.resizeTask(taskId, null /* bounds */, 0 /* resizeMode */));
         assertNotRestoreTask(
-                () -> mService.setTaskWindowingMode(taskId, WINDOWING_MODE_FULLSCREEN,
+                () -> mTestService.setTaskWindowingMode(taskId, WINDOWING_MODE_FULLSCREEN,
                         false/* toTop */));
         assertNotRestoreTask(
-                () -> mService.setTaskWindowingModeSplitScreenPrimary(taskId,
+                () -> mTestService.setTaskWindowingModeSplitScreenPrimary(taskId,
                         SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT,
                         false /* toTop */, false /* animate */, null /* initialBounds */,
                         true /* showRecents */));
@@ -699,87 +696,90 @@
 
     @Test
     public void testNotRecentsComponent_denyApiAccess() throws Exception {
-        doReturn(PackageManager.PERMISSION_DENIED).when(mService)
+        doReturn(PackageManager.PERMISSION_DENIED).when(mTestService)
                 .checkGetTasksPermission(anyString(), anyInt(), anyInt());
         // Expect the following methods to fail due to recents component not being set
         mRecentTasks.setIsCallerRecentsOverride(TestRecentTasks.DENY_THROW_SECURITY_EXCEPTION);
-        testRecentTasksApis(false /* expectNoSecurityException */);
+        doTestRecentTasksApis(false /* expectNoSecurityException */);
         // Don't throw for the following tests
         mRecentTasks.setIsCallerRecentsOverride(TestRecentTasks.DENY);
         testGetTasksApis(false /* expectNoSecurityException */);
     }
 
     @Test
-    public void testRecentsComponent_allowApiAccessWithoutPermissions() throws Exception {
-        doReturn(PackageManager.PERMISSION_DENIED).when(mService)
+    public void testRecentsComponent_allowApiAccessWithoutPermissions() {
+        doReturn(PackageManager.PERMISSION_DENIED).when(mTestService)
                 .checkGetTasksPermission(anyString(), anyInt(), anyInt());
 
         // Set the recents component and ensure that the following calls do not fail
         mRecentTasks.setIsCallerRecentsOverride(TestRecentTasks.GRANT);
-        testRecentTasksApis(true /* expectNoSecurityException */);
+        doTestRecentTasksApis(true /* expectNoSecurityException */);
         testGetTasksApis(true /* expectNoSecurityException */);
     }
 
-    private void testRecentTasksApis(boolean expectCallable) {
-        assertSecurityException(expectCallable, () -> mService.removeStack(INVALID_STACK_ID));
+    private void doTestRecentTasksApis(boolean expectCallable) {
+        assertSecurityException(expectCallable, () -> mTestService.removeStack(INVALID_STACK_ID));
         assertSecurityException(expectCallable,
-                () -> mService.removeStacksInWindowingModes(new int[] {WINDOWING_MODE_UNDEFINED}));
+                () -> mTestService.removeStacksInWindowingModes(
+                        new int[]{WINDOWING_MODE_UNDEFINED}));
         assertSecurityException(expectCallable,
-                () -> mService.removeStacksWithActivityTypes(new int[] {ACTIVITY_TYPE_UNDEFINED}));
-        assertSecurityException(expectCallable, () -> mService.removeTask(0));
+                () -> mTestService.removeStacksWithActivityTypes(
+                        new int[]{ACTIVITY_TYPE_UNDEFINED}));
+        assertSecurityException(expectCallable, () -> mTestService.removeTask(0));
         assertSecurityException(expectCallable,
-                () -> mService.setTaskWindowingMode(0, WINDOWING_MODE_UNDEFINED, true));
+                () -> mTestService.setTaskWindowingMode(0, WINDOWING_MODE_UNDEFINED, true));
         assertSecurityException(expectCallable,
-                () -> mService.moveTaskToStack(0, INVALID_STACK_ID, true));
+                () -> mTestService.moveTaskToStack(0, INVALID_STACK_ID, true));
         assertSecurityException(expectCallable,
-                () -> mService.setTaskWindowingModeSplitScreenPrimary(0,
+                () -> mTestService.setTaskWindowingModeSplitScreenPrimary(0,
                         SPLIT_SCREEN_CREATE_MODE_TOP_OR_LEFT, true, true, new Rect(), true));
-        assertSecurityException(expectCallable, () -> mService.dismissSplitScreenMode(true));
-        assertSecurityException(expectCallable, () -> mService.dismissPip(true, 0));
+        assertSecurityException(expectCallable, () -> mTestService.dismissSplitScreenMode(true));
+        assertSecurityException(expectCallable, () -> mTestService.dismissPip(true, 0));
         assertSecurityException(expectCallable,
-                () -> mService.moveTopActivityToPinnedStack(INVALID_STACK_ID, new Rect()));
+                () -> mTestService.moveTopActivityToPinnedStack(INVALID_STACK_ID, new Rect()));
         assertSecurityException(expectCallable,
-                () -> mService.resizeStack(INVALID_STACK_ID, new Rect(), true, true, true, 0));
+                () -> mTestService.resizeStack(INVALID_STACK_ID, new Rect(), true, true, true, 0));
         assertSecurityException(expectCallable,
-                () -> mService.resizeDockedStack(new Rect(), new Rect(), new Rect(), new Rect(),
+                () -> mTestService.resizeDockedStack(new Rect(), new Rect(), new Rect(), new Rect(),
                         new Rect()));
         assertSecurityException(expectCallable,
-                () -> mService.resizePinnedStack(new Rect(), new Rect()));
-        assertSecurityException(expectCallable, () -> mService.getAllStackInfos());
+                () -> mTestService.resizePinnedStack(new Rect(), new Rect()));
+        assertSecurityException(expectCallable, () -> mTestService.getAllStackInfos());
         assertSecurityException(expectCallable,
-                () -> mService.getStackInfo(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_UNDEFINED));
+                () -> mTestService.getStackInfo(WINDOWING_MODE_UNDEFINED, ACTIVITY_TYPE_UNDEFINED));
         assertSecurityException(expectCallable, () -> {
             try {
-                mService.getFocusedStackInfo();
+                mTestService.getFocusedStackInfo();
             } catch (RemoteException e) {
                 // Ignore
             }
         });
         assertSecurityException(expectCallable,
-                () -> mService.moveTasksToFullscreenStack(INVALID_STACK_ID, true));
+                () -> mTestService.moveTasksToFullscreenStack(INVALID_STACK_ID, true));
         assertSecurityException(expectCallable,
-                () -> mService.startActivityFromRecents(0, new Bundle()));
-        assertSecurityException(expectCallable,() -> mService.getTaskSnapshot(0, true));
-        assertSecurityException(expectCallable,() -> mService.registerTaskStackListener(null));
-        assertSecurityException(expectCallable,() -> mService.unregisterTaskStackListener(null));
-        assertSecurityException(expectCallable, () -> mService.getTaskDescription(0));
-        assertSecurityException(expectCallable, () -> mService.cancelTaskWindowTransition(0));
-        assertSecurityException(expectCallable, () -> mService.startRecentsActivity(null, null,
+                () -> mTestService.startActivityFromRecents(0, new Bundle()));
+        assertSecurityException(expectCallable, () -> mTestService.getTaskSnapshot(0, true));
+        assertSecurityException(expectCallable, () -> mTestService.registerTaskStackListener(null));
+        assertSecurityException(expectCallable,
+                () -> mTestService.unregisterTaskStackListener(null));
+        assertSecurityException(expectCallable, () -> mTestService.getTaskDescription(0));
+        assertSecurityException(expectCallable, () -> mTestService.cancelTaskWindowTransition(0));
+        assertSecurityException(expectCallable, () -> mTestService.startRecentsActivity(null, null,
                 null));
-        assertSecurityException(expectCallable, () -> mService.cancelRecentsAnimation(true));
-        assertSecurityException(expectCallable, () -> mService.stopAppSwitches());
-        assertSecurityException(expectCallable, () -> mService.resumeAppSwitches());
+        assertSecurityException(expectCallable, () -> mTestService.cancelRecentsAnimation(true));
+        assertSecurityException(expectCallable, () -> mTestService.stopAppSwitches());
+        assertSecurityException(expectCallable, () -> mTestService.resumeAppSwitches());
     }
 
     private void testGetTasksApis(boolean expectCallable) {
-        mService.getRecentTasks(MAX_VALUE, 0, TEST_USER_0_ID);
-        mService.getTasks(MAX_VALUE);
+        mTestService.getRecentTasks(MAX_VALUE, 0, TEST_USER_0_ID);
+        mTestService.getTasks(MAX_VALUE);
         if (expectCallable) {
-            assertTrue(mRecentTasks.lastAllowed);
-            assertTrue(mRunningTasks.lastAllowed);
+            assertTrue(mRecentTasks.mLastAllowed);
+            assertTrue(mRunningTasks.mLastAllowed);
         } else {
-            assertFalse(mRecentTasks.lastAllowed);
-            assertFalse(mRunningTasks.lastAllowed);
+            assertFalse(mRecentTasks.mLastAllowed);
+            assertFalse(mRunningTasks.mLastAllowed);
         }
     }
 
@@ -788,10 +788,10 @@
     }
 
     private TaskBuilder createTaskBuilder(String packageName, String className) {
-        return new TaskBuilder(mService.mStackSupervisor)
+        return new TaskBuilder(mTestService.mStackSupervisor)
                 .setComponent(new ComponentName(packageName, className))
                 .setStack(mStack)
-                .setTaskId(LAST_TASK_ID++)
+                .setTaskId(sLastTaskId++)
                 .setUserId(TEST_USER_0_ID);
     }
 
@@ -824,25 +824,20 @@
         return task;
     }
 
-    private boolean arrayContainsUser(int[] userIds, int targetUserId) {
-        Arrays.sort(userIds);
-        return Arrays.binarySearch(userIds, targetUserId) >= 0;
-    }
-
     private void assertNoTasksTrimmed() {
         assertTrimmed();
     }
 
     private void assertTrimmed(TaskRecord... tasks) {
-        final ArrayList<TaskRecord> trimmed = mCallbacksRecorder.trimmed;
-        final ArrayList<TaskRecord> removed = mCallbacksRecorder.removed;
-        assertTrue("Expected " + tasks.length + " trimmed tasks, got " + trimmed.size(),
-                trimmed.size() == tasks.length);
-        assertTrue("Expected " + tasks.length + " removed tasks, got " + removed.size(),
-                removed.size() == tasks.length);
+        final ArrayList<TaskRecord> trimmed = mCallbacksRecorder.mTrimmed;
+        final ArrayList<TaskRecord> removed = mCallbacksRecorder.mRemoved;
+        assertWithMessage("Expected " + tasks.length + " trimmed tasks, got " + trimmed.size())
+                .that(trimmed).hasSize(tasks.length);
+        assertWithMessage("Expected " + tasks.length + " removed tasks, got " + removed.size())
+                .that(removed).hasSize(tasks.length);
         for (TaskRecord task : tasks) {
-            assertTrue("Expected trimmed task: " + task, trimmed.contains(task));
-            assertTrue("Expected removed task: " + task, removed.contains(task));
+            assertWithMessage("Expected trimmed task: " + task).that(trimmed).contains(task);
+            assertWithMessage("Expected removed task: " + task).that(removed).contains(task);
         }
     }
 
@@ -853,8 +848,7 @@
         } catch (SecurityException se) {
             noSecurityException = false;
         } catch (Exception e) {
-            // We only care about SecurityExceptions, fall through here
-            e.printStackTrace();
+            // We only care about SecurityExceptions, fall through here.
         }
         if (noSecurityException != expectCallable) {
             fail("Expected callable: " + expectCallable + " but got no security exception: "
@@ -891,7 +885,7 @@
     }
 
     private class MyTestActivityStackSupervisor extends TestActivityStackSupervisor {
-        public MyTestActivityStackSupervisor(ActivityTaskManagerService service, Looper looper) {
+        MyTestActivityStackSupervisor(ActivityTaskManagerService service, Looper looper) {
             super(service, looper);
         }
 
@@ -911,11 +905,11 @@
         }
     }
 
-    private class MyTestActivityStack extends TestActivityStack {
+    private static class MyTestActivityStack extends TestActivityStack {
         private ActivityDisplay mDisplay = null;
 
         MyTestActivityStack(ActivityDisplay display, ActivityStackSupervisor supervisor) {
-            super(display, LAST_STACK_ID++, supervisor, WINDOWING_MODE_FULLSCREEN,
+            super(display, sLastStackId++, supervisor, WINDOWING_MODE_FULLSCREEN,
                     ACTIVITY_TYPE_STANDARD, true /* onTop */, false /* createActivity */);
             mDisplay = display;
         }
@@ -930,33 +924,33 @@
     }
 
     private static class CallbacksRecorder implements Callbacks {
-        ArrayList<TaskRecord> added = new ArrayList<>();
-        ArrayList<TaskRecord> trimmed = new ArrayList<>();
-        ArrayList<TaskRecord> removed = new ArrayList<>();
+        public final ArrayList<TaskRecord> mAdded = new ArrayList<>();
+        public final ArrayList<TaskRecord> mTrimmed = new ArrayList<>();
+        public final ArrayList<TaskRecord> mRemoved = new ArrayList<>();
 
         void clear() {
-            added.clear();
-            trimmed.clear();
-            removed.clear();
+            mAdded.clear();
+            mTrimmed.clear();
+            mRemoved.clear();
         }
 
         @Override
         public void onRecentTaskAdded(TaskRecord task) {
-            added.add(task);
+            mAdded.add(task);
         }
 
         @Override
         public void onRecentTaskRemoved(TaskRecord task, boolean wasTrimmed, boolean killProcess) {
             if (wasTrimmed) {
-                trimmed.add(task);
+                mTrimmed.add(task);
             }
-            removed.add(task);
+            mRemoved.add(task);
         }
     }
 
     private static class TestTaskPersister extends TaskPersister {
-        SparseBooleanArray userTaskIdsOverride;
-        ArrayList<TaskRecord> userTasksOverride;
+        public SparseBooleanArray mUserTaskIdsOverride;
+        public ArrayList<TaskRecord> mUserTasksOverride;
 
         TestTaskPersister(File workingDir) {
             super(workingDir);
@@ -964,16 +958,16 @@
 
         @Override
         SparseBooleanArray loadPersistedTaskIdsForUser(int userId) {
-            if (userTaskIdsOverride != null) {
-                return userTaskIdsOverride;
+            if (mUserTaskIdsOverride != null) {
+                return mUserTaskIdsOverride;
             }
             return super.loadPersistedTaskIdsForUser(userId);
         }
 
         @Override
         List<TaskRecord> restoreTasksForUserLocked(int userId, SparseBooleanArray preaddedTasks) {
-            if (userTasksOverride != null) {
-                return userTasksOverride;
+            if (mUserTasksOverride != null) {
+                return mUserTasksOverride;
             }
             return super.restoreTasksForUserLocked(userId, preaddedTasks);
         }
@@ -988,7 +982,7 @@
         private boolean mIsTrimmableOverride;
         private int mIsCallerRecentsPolicy;
 
-        boolean lastAllowed;
+        public boolean mLastAllowed;
 
         TestRecentTasks(ActivityTaskManagerService service, TaskPersister taskPersister) {
             super(service, taskPersister);
@@ -1053,7 +1047,7 @@
         ParceledListSlice<RecentTaskInfo> getRecentTasks(int maxNum, int flags,
                 boolean getTasksAllowed,
                 boolean getDetailedTasks, int userId, int callingUid) {
-            lastAllowed = getTasksAllowed;
+            mLastAllowed = getTasksAllowed;
             return super.getRecentTasks(maxNum, flags, getTasksAllowed, getDetailedTasks, userId,
                     callingUid);
         }
@@ -1065,13 +1059,13 @@
     }
 
     private static class TestRunningTasks extends RunningTasks {
-        boolean lastAllowed;
+        public boolean mLastAllowed;
 
         @Override
         void getTasks(int maxNum, List<RunningTaskInfo> list, int ignoreActivityType,
                 int ignoreWindowingMode, ArrayList<ActivityDisplay> activityDisplays,
                 int callingUid, boolean allowed) {
-            lastAllowed = allowed;
+            mLastAllowed = allowed;
             super.getTasks(maxNum, list, ignoreActivityType, ignoreWindowingMode, activityDisplays,
                     callingUid, allowed);
         }
diff --git a/services/tests/servicestests/src/com/android/server/am/RecentsAnimationTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java
similarity index 68%
rename from services/tests/servicestests/src/com/android/server/am/RecentsAnimationTest.java
rename to services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java
index f15b5f7..a01a3d9 100644
--- a/services/tests/servicestests/src/com/android/server/am/RecentsAnimationTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -11,10 +11,10 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_RECENTS;
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
@@ -38,63 +38,60 @@
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 /**
- * atest FrameworksServicesTests:RecentsAnimationTest
+ * Build/Install/Run:
+ *  atest WmTests:RecentsAnimationTest
  */
 @MediumTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class RecentsAnimationTest extends ActivityTestsBase {
 
     private Context mContext = InstrumentationRegistry.getContext();
-    private TestActivityTaskManagerService mService;
+    private TestActivityTaskManagerService mTestService;
     private ComponentName mRecentsComponent;
 
     @Before
-    @Override
     public void setUp() throws Exception {
-        super.setUp();
-
         mRecentsComponent = new ComponentName(mContext.getPackageName(), "RecentsActivity");
-        mService = spy(new MyTestActivityTaskManagerService(mContext));
-        setupActivityManagerService(mService);
+        mTestService = spy(new MyTestActivityTaskManagerService(mContext));
+        setupActivityManagerService(mTestService);
     }
 
     @Test
-    public void testCancelAnimationOnStackOrderChange() throws Exception {
-        ActivityStack fullscreenStack = mService.mStackSupervisor.getDefaultDisplay().createStack(
-                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
-        ActivityStack recentsStack = mService.mStackSupervisor.getDefaultDisplay().createStack(
+    public void testCancelAnimationOnStackOrderChange() {
+        ActivityStack fullscreenStack =
+                mTestService.mStackSupervisor.getDefaultDisplay().createStack(
+                        WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
+        ActivityStack recentsStack = mTestService.mStackSupervisor.getDefaultDisplay().createStack(
                 WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_RECENTS, true /* onTop */);
-        ActivityRecord recentsActivity = new ActivityBuilder(mService)
+        ActivityRecord recentsActivity = new ActivityBuilder(mTestService)
                 .setComponent(mRecentsComponent)
                 .setCreateTask(true)
                 .setStack(recentsStack)
                 .build();
-        ActivityStack fullscreenStack2 = mService.mStackSupervisor.getDefaultDisplay().createStack(
-                WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
-        ActivityRecord fsActivity = new ActivityBuilder(mService)
+        ActivityStack fullscreenStack2 =
+                mTestService.mStackSupervisor.getDefaultDisplay().createStack(
+                        WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_STANDARD, true /* onTop */);
+        ActivityRecord fsActivity = new ActivityBuilder(mTestService)
                 .setComponent(new ComponentName(mContext.getPackageName(), "App1"))
                 .setCreateTask(true)
                 .setStack(fullscreenStack2)
                 .build();
-        doReturn(true).when(mService.mWindowManager).canStartRecentsAnimation();
+        doReturn(true).when(mTestService.mWindowManager).canStartRecentsAnimation();
 
         // Start the recents animation
         Intent recentsIntent = new Intent();
         recentsIntent.setComponent(mRecentsComponent);
-        mService.startRecentsActivity(recentsIntent, null, mock(IRecentsAnimationRunner.class));
+        mTestService.startRecentsActivity(recentsIntent, null, mock(IRecentsAnimationRunner.class));
 
         fullscreenStack.moveToFront("Activity start");
 
         // Ensure that the recents animation was canceled
-        verify(mService.mWindowManager, times(1)).cancelRecentsAnimationSynchronously(
+        verify(mTestService.mWindowManager, times(1)).cancelRecentsAnimationSynchronously(
                 eq(REORDER_KEEP_IN_PLACE), any());
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/am/RunningTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java
similarity index 80%
rename from services/tests/servicestests/src/com/android/server/am/RunningTasksTest.java
rename to services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java
index 849a411..0e1624e 100644
--- a/services/tests/servicestests/src/com/android/server/am/RunningTasksTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/RunningTasksTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -11,57 +11,50 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_UNDEFINED;
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
 import static android.view.Display.DEFAULT_DISPLAY;
 
-import static com.android.server.am.ActivityDisplay.POSITION_BOTTOM;
+import static com.android.server.wm.ActivityDisplay.POSITION_BOTTOM;
 
-import static org.junit.Assert.assertTrue;
+import static com.google.common.truth.Truth.assertThat;
+
+import static org.junit.Assert.assertEquals;
 
 import android.app.ActivityManager.RunningTaskInfo;
 import android.content.ComponentName;
-import android.content.Context;
 import android.platform.test.annotations.Presubmit;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 
 /**
- * atest FrameworksServicesTests:RunningTasksTest
+ * Build/Install/Run:
+ *  atest WmTests:RunningTasksTest
  */
 @MediumTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class RunningTasksTest extends ActivityTestsBase {
 
-    private Context mContext = InstrumentationRegistry.getContext();
-
     private RunningTasks mRunningTasks;
 
     @Before
-    @Override
     public void setUp() throws Exception {
-        super.setUp();
-
         setupActivityTaskManagerService();
         mRunningTasks = new RunningTasks();
     }
 
     @Test
-    public void testCollectTasksByLastActiveTime() throws Exception {
+    public void testCollectTasksByLastActiveTime() {
         // Create a number of stacks with tasks (of incrementing active time)
         final ArrayList<ActivityDisplay> displays = new ArrayList<>();
         final ActivityDisplay display = TestActivityDisplay.create(mSupervisor, DEFAULT_DISPLAY);
@@ -86,9 +79,9 @@
         ArrayList<RunningTaskInfo> tasks = new ArrayList<>();
         mRunningTasks.getTasks(5, tasks, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED,
                 displays, -1 /* callingUid */, true /* allowed */);
-        assertTrue(tasks.size() == numFetchTasks);
+        assertThat(tasks).hasSize(numFetchTasks);
         for (int i = 0; i < numFetchTasks; i++) {
-            assertTrue(tasks.get(i).id == (numTasks - i - 1));
+            assertEquals(numTasks - i - 1, tasks.get(i).id);
         }
 
         // Ensure that requesting more than the total number of tasks only returns the subset
@@ -96,9 +89,9 @@
         tasks.clear();
         mRunningTasks.getTasks(100, tasks, ACTIVITY_TYPE_UNDEFINED, WINDOWING_MODE_UNDEFINED,
                 displays, -1 /* callingUid */, true /* allowed */);
-        assertTrue(tasks.size() == numTasks);
+        assertThat(tasks).hasSize(numTasks);
         for (int i = 0; i < numTasks; i++) {
-            assertTrue(tasks.get(i).id == (numTasks - i - 1));
+            assertEquals(numTasks - i - 1, tasks.get(i).id);
         }
     }
 
@@ -119,4 +112,4 @@
                 .build();
         return task;
     }
-}
\ No newline at end of file
+}
diff --git a/services/tests/servicestests/src/com/android/server/am/SafeActivityOptionsTest.java b/services/tests/wmtests/src/com/android/server/wm/SafeActivityOptionsTest.java
similarity index 90%
rename from services/tests/servicestests/src/com/android/server/am/SafeActivityOptionsTest.java
rename to services/tests/wmtests/src/com/android/server/wm/SafeActivityOptionsTest.java
index 8e4e7e6..530fd6d 100644
--- a/services/tests/servicestests/src/com/android/server/am/SafeActivityOptionsTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/SafeActivityOptionsTest.java
@@ -14,7 +14,7 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static org.junit.Assert.assertEquals;
 
@@ -23,15 +23,16 @@
 
 import androidx.test.filters.FlakyTest;
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
+/**
+ * Build/Install/Run:
+ *  atest WmTests:SafeActivityOptionsTest
+ */
 @MediumTest
-@Presubmit
 @FlakyTest
-@RunWith(AndroidJUnit4.class)
+@Presubmit
 public class SafeActivityOptionsTest {
 
     @Test
diff --git a/services/tests/servicestests/src/com/android/server/wm/ScreenDecorWindowTests.java b/services/tests/wmtests/src/com/android/server/wm/ScreenDecorWindowTests.java
similarity index 90%
rename from services/tests/servicestests/src/com/android/server/wm/ScreenDecorWindowTests.java
rename to services/tests/wmtests/src/com/android/server/wm/ScreenDecorWindowTests.java
index ae40f7e..36eccd1 100644
--- a/services/tests/servicestests/src/com/android/server/wm/ScreenDecorWindowTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/ScreenDecorWindowTests.java
@@ -11,7 +11,7 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
 package com.android.server.wm;
@@ -33,6 +33,8 @@
 import static android.view.WindowManager.LayoutParams.PRIVATE_FLAG_IS_SCREEN_DECOR;
 import static android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
 
+import static com.google.common.truth.Truth.assertThat;
+
 import static org.junit.Assert.assertEquals;
 
 import android.app.Activity;
@@ -46,6 +48,7 @@
 import android.hardware.display.VirtualDisplay;
 import android.media.ImageReader;
 import android.os.Handler;
+import android.os.SystemClock;
 import android.platform.test.annotations.Presubmit;
 import android.util.Pair;
 import android.view.Display;
@@ -57,13 +60,10 @@
 
 import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.After;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.ArrayList;
 import java.util.function.BooleanSupplier;
@@ -72,13 +72,12 @@
  * Tests for the {@link android.view.WindowManager.LayoutParams#PRIVATE_FLAG_IS_SCREEN_DECOR} flag.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:com.android.server.wm.ScreenDecorWindowTests
+ *  atest WmTests:ScreenDecorWindowTests
  */
 // TODO: Add test for FLAG_FULLSCREEN which hides the status bar and also other flags.
 // TODO: Test non-Activity windows.
 @SmallTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class ScreenDecorWindowTests {
 
     private final Context mContext = InstrumentationRegistry.getTargetContext();
@@ -120,7 +119,7 @@
     }
 
     @Test
-    public void testScreenSides() throws Exception {
+    public void testScreenSides() {
         // Decor on top
         final View decorWindow = createDecorWindow(TOP, MATCH_PARENT, mDecorThickness);
         assertInsetGreaterOrEqual(mTestActivity, TOP, mDecorThickness);
@@ -139,7 +138,7 @@
     }
 
     @Test
-    public void testMultipleDecors() throws Exception {
+    public void testMultipleDecors() {
         // Test 2 decor windows on-top.
         createDecorWindow(TOP, MATCH_PARENT, mHalfDecorThickness);
         assertInsetGreaterOrEqual(mTestActivity, TOP, mHalfDecorThickness);
@@ -153,7 +152,7 @@
     }
 
     @Test
-    public void testFlagChange() throws Exception {
+    public void testFlagChange() {
         WindowInsets initialInsets = getInsets(mTestActivity);
 
         final View decorWindow = createDecorWindow(TOP, MATCH_PARENT, mDecorThickness);
@@ -174,7 +173,7 @@
     }
 
     @Test
-    public void testRemoval() throws Exception {
+    public void testRemoval() {
         WindowInsets initialInsets = getInsets(mTestActivity);
 
         final View decorWindow = createDecorWindow(TOP, MATCH_PARENT, mDecorThickness);
@@ -256,7 +255,7 @@
     /**
      * Asserts the top inset of {@param activity} is equal to {@param expected} waiting as needed.
      */
-    private void assertTopInsetEquals(Activity activity, int expected) throws Exception {
+    private void assertTopInsetEquals(Activity activity, int expected) {
         waitForTopInsetEqual(activity, expected);
         assertEquals(expected, getInsets(activity).getSystemWindowInsetTop());
     }
@@ -269,16 +268,23 @@
      * Asserts the inset at {@param side} of {@param activity} is equal to {@param expected}
      * waiting as needed.
      */
-    private void assertInsetGreaterOrEqual(Activity activity, int side, int expected)
-            throws Exception {
+    private void assertInsetGreaterOrEqual(Activity activity, int side, int expected) {
         waitForInsetGreaterOrEqual(activity, side, expected);
 
         final WindowInsets insets = getInsets(activity);
         switch (side) {
-            case TOP: assertGreaterOrEqual(insets.getSystemWindowInsetTop(), expected); break;
-            case BOTTOM: assertGreaterOrEqual(insets.getSystemWindowInsetBottom(), expected); break;
-            case LEFT: assertGreaterOrEqual(insets.getSystemWindowInsetLeft(), expected); break;
-            case RIGHT: assertGreaterOrEqual(insets.getSystemWindowInsetRight(), expected); break;
+            case TOP:
+                assertThat(insets.getSystemWindowInsetTop()).isAtLeast(expected);
+                break;
+            case BOTTOM:
+                assertThat(insets.getSystemWindowInsetBottom()).isAtLeast(expected);
+                break;
+            case LEFT:
+                assertThat(insets.getSystemWindowInsetLeft()).isAtLeast(expected);
+                break;
+            case RIGHT:
+                assertThat(insets.getSystemWindowInsetRight()).isAtLeast(expected);
+                break;
         }
     }
 
@@ -295,22 +301,13 @@
         });
     }
 
-    /** Asserts that the first entry is greater than or equal to the second entry. */
-    private void assertGreaterOrEqual(int first, int second) throws Exception {
-        Assert.assertTrue("Excepted " + first + " >= " + second, first >= second);
-    }
-
     private void waitFor(BooleanSupplier waitCondition) {
         int retriesLeft = 5;
         do {
             if (waitCondition.getAsBoolean()) {
                 break;
             }
-            try {
-                Thread.sleep(500);
-            } catch (InterruptedException e) {
-                // Well I guess we are not waiting...
-            }
+            SystemClock.sleep(500);
         } while (retriesLeft-- > 0);
     }
 
diff --git a/services/tests/servicestests/src/com/android/server/am/TaskLaunchParamsModifierTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
similarity index 97%
rename from services/tests/servicestests/src/com/android/server/am/TaskLaunchParamsModifierTests.java
rename to services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
index b7f2b35..95965c8 100644
--- a/services/tests/servicestests/src/com/android/server/am/TaskLaunchParamsModifierTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskLaunchParamsModifierTests.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -11,10 +11,10 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.app.WindowConfiguration.ACTIVITY_TYPE_STANDARD;
 import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM;
@@ -22,17 +22,14 @@
 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
 import static android.content.pm.ActivityInfo.RESIZE_MODE_UNRESIZEABLE;
-import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
-import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LOCKED;
 import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
 import static android.util.DisplayMetrics.DENSITY_DEFAULT;
 import static android.view.Display.DEFAULT_DISPLAY;
 
-import static com.android.server.am.LaunchParamsController.LaunchParamsModifier.RESULT_CONTINUE;
-import static com.android.server.am.LaunchParamsController.LaunchParamsModifier.RESULT_SKIP;
+import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_CONTINUE;
+import static com.android.server.wm.LaunchParamsController.LaunchParamsModifier.RESULT_SKIP;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.ArgumentMatchers.any;
 import static org.mockito.Mockito.when;
@@ -46,15 +43,13 @@
 import android.platform.test.annotations.Presubmit;
 import android.view.Gravity;
 
-import androidx.test.filters.SmallTest;
 import androidx.test.filters.FlakyTest;
-import androidx.test.runner.AndroidJUnit4;
+import androidx.test.filters.SmallTest;
 
-import com.android.server.am.LaunchParamsController.LaunchParams;
+import com.android.server.wm.LaunchParamsController.LaunchParams;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.Locale;
 
@@ -62,12 +57,11 @@
  * Tests for default task bounds.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:TaskLaunchParamsModifierTests
+ *  atest WmTests:TaskLaunchParamsModifierTests
  */
 @SmallTest
-@Presubmit
-@RunWith(AndroidJUnit4.class)
 @FlakyTest(detail = "Confirm stable in post-submit before removing")
+@Presubmit
 public class TaskLaunchParamsModifierTests extends ActivityTestsBase {
 
     private ActivityRecord mActivity;
@@ -78,10 +72,7 @@
     private LaunchParams mResult;
 
     @Before
-    @Override
     public void setUp() throws Exception {
-        super.setUp();
-
         setupActivityTaskManagerService();
         mService.mSupportsFreeformWindowManagement = true;
         when(mSupervisor.canUseActivityOptionsLaunchBounds(any())).thenCallRealMethod();
@@ -1027,8 +1018,7 @@
         assertEquals(RESULT_CONTINUE, mTarget.onCalculate(/* task */ null, /* layout */ null,
                 mActivity, /* source */ null, options, mCurrent, mResult));
 
-        assertEquals(new Rect(0, 0, 1680,
-                953), mResult.mBounds);
+        assertEquals(new Rect(0, 0, 1680, 953), mResult.mBounds);
     }
 
     private TestActivityDisplay createNewActivityDisplay(int windowingMode) {
diff --git a/services/tests/servicestests/src/com/android/server/am/TaskPersisterTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskPersisterTest.java
similarity index 77%
rename from services/tests/servicestests/src/com/android/server/am/TaskPersisterTest.java
rename to services/tests/wmtests/src/com/android/server/wm/TaskPersisterTest.java
index 48bfe1d..df7bc11 100644
--- a/services/tests/servicestests/src/com/android/server/am/TaskPersisterTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskPersisterTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -11,59 +11,61 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
+
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
-import static androidx.test.InstrumentationRegistry.getTargetContext;
-
+import android.content.Context;
 import android.content.pm.UserInfo;
 import android.os.UserHandle;
 import android.os.UserManager;
 import android.platform.test.annotations.Presubmit;
 import android.util.SparseBooleanArray;
 
+import androidx.test.filters.FlakyTest;
+
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
 
-import androidx.test.filters.FlakyTest;
-
 /**
  * Tests for {@link TaskPersister}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:TaskPersisterTest
+ *  atest WmTests:TaskPersisterTest
  */
-@Presubmit
 @FlakyTest(detail = "Promote to presubmit if stable")
+@Presubmit
 public class TaskPersisterTest {
     private static final String TEST_USER_NAME = "AM-Test-User";
 
     private TaskPersister mTaskPersister;
-    private int testUserId;
+    private int mTestUserId;
     private UserManager mUserManager;
 
     @Before
     public void setUp() throws Exception {
-        mUserManager = UserManager.get(getTargetContext());
-        mTaskPersister = new TaskPersister(getTargetContext().getFilesDir());
+        final Context context = getInstrumentation().getTargetContext();
+        mUserManager = UserManager.get(context);
+        mTaskPersister = new TaskPersister(context.getFilesDir());
         // In ARC, the maximum number of supported users is one, which is different from the ones of
         // most phones (more than 4). This prevents TaskPersisterTest from creating another user for
         // test. However, since guest users can be added as much as possible, we create guest user
         // in the test.
-        testUserId = createUser(TEST_USER_NAME, UserInfo.FLAG_GUEST);
+        mTestUserId = createUser(TEST_USER_NAME, UserInfo.FLAG_GUEST);
     }
 
     @After
     public void tearDown() throws Exception {
-        mTaskPersister.unloadUserDataFromMemory(testUserId);
-        removeUser(testUserId);
+        mTaskPersister.unloadUserDataFromMemory(mTestUserId);
+        removeUser(mTestUserId);
     }
 
     private int getRandomTaskIdForUser(int userId) {
@@ -76,11 +78,11 @@
     public void testTaskIdsPersistence() {
         SparseBooleanArray taskIdsOnFile = new SparseBooleanArray();
         for (int i = 0; i < 100; i++) {
-            taskIdsOnFile.put(getRandomTaskIdForUser(testUserId), true);
+            taskIdsOnFile.put(getRandomTaskIdForUser(mTestUserId), true);
         }
-        mTaskPersister.writePersistedTaskIdsForUser(taskIdsOnFile, testUserId);
+        mTaskPersister.writePersistedTaskIdsForUser(taskIdsOnFile, mTestUserId);
         SparseBooleanArray newTaskIdsOnFile = mTaskPersister
-                .loadPersistedTaskIdsForUser(testUserId);
+                .loadPersistedTaskIdsForUser(mTestUserId);
         assertEquals("TaskIds written differ from TaskIds read back from file",
                 taskIdsOnFile, newTaskIdsOnFile);
     }
diff --git a/services/tests/servicestests/src/com/android/server/am/TaskRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java
similarity index 92%
rename from services/tests/servicestests/src/com/android/server/am/TaskRecordTests.java
rename to services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java
index 27766d3..4455630 100644
--- a/services/tests/servicestests/src/com/android/server/am/TaskRecordTests.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -11,11 +11,10 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License.
- *
+ * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
 import static android.content.Intent.FLAG_ACTIVITY_NEW_TASK;
 import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME;
@@ -35,14 +34,12 @@
 import android.util.Xml;
 
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.app.IVoiceInteractor;
-import com.android.server.am.TaskRecord.TaskRecordFactory;
+import com.android.server.wm.TaskRecord.TaskRecordFactory;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 import org.xmlpull.v1.XmlPullParser;
 import org.xmlpull.v1.XmlPullParserException;
 import org.xmlpull.v1.XmlSerializer;
@@ -60,18 +57,16 @@
  * Tests for exercising {@link TaskRecord}.
  *
  * Build/Install/Run:
- *  atest FrameworksServicesTests:com.android.server.am.TaskRecordTests
+ *  atest WmTests:TaskRecordTests
  */
 @MediumTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class TaskRecordTests extends ActivityTestsBase {
 
     private static final String TASK_TAG = "task";
 
     @Before
     public void setUp() throws Exception {
-        super.setUp();
         TaskRecord.setTaskRecordFactory(null);
         setupActivityTaskManagerService();
     }
@@ -124,7 +119,7 @@
     private File serializeToFile(TaskRecord r) throws IOException, XmlPullParserException {
         final File tmpFile = File.createTempFile(r.taskId + "_task_", "xml");
 
-        try (final OutputStream os = new FileOutputStream(tmpFile)) {
+        try (OutputStream os = new FileOutputStream(tmpFile)) {
             final XmlSerializer serializer = Xml.newSerializer();
             serializer.setOutput(os, "UTF-8");
             serializer.startDocument(null, true);
@@ -138,7 +133,7 @@
     }
 
     private TaskRecord restoreFromFile(File file) throws IOException, XmlPullParserException {
-        try (final Reader reader = new BufferedReader(new FileReader(file))) {
+        try (Reader reader = new BufferedReader(new FileReader(file))) {
             final XmlPullParser parser = Xml.newPullParser();
             parser.setInput(reader);
             assertEquals(XmlPullParser.START_TAG, parser.next());
diff --git a/services/tests/servicestests/src/com/android/server/am/TaskStackChangedListenerTest.java b/services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java
similarity index 86%
rename from services/tests/servicestests/src/com/android/server/am/TaskStackChangedListenerTest.java
rename to services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java
index 3f7c714..4a734e5 100644
--- a/services/tests/servicestests/src/com/android/server/am/TaskStackChangedListenerTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/TaskStackChangedListenerTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2016 The Android Open Source Project
+ * Copyright (C) 2018 The Android Open Source Project
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -14,9 +14,9 @@
  * limitations under the License
  */
 
-package com.android.server.am;
+package com.android.server.wm;
 
-import static androidx.test.InstrumentationRegistry.getInstrumentation;
+import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
@@ -38,23 +38,22 @@
 import android.support.test.uiautomator.UiDevice;
 import android.text.TextUtils;
 
-import androidx.test.InstrumentationRegistry;
 import androidx.test.filters.MediumTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import com.android.internal.annotations.GuardedBy;
 
 import org.junit.After;
-import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
+/**
+ * Build/Install/Run:
+ *  atest WmTests:TaskStackChangedListenerTest
+ */
 @MediumTest
-@RunWith(AndroidJUnit4.class)
 public class TaskStackChangedListenerTest {
 
     private IActivityManager mService;
@@ -87,13 +86,13 @@
             }
         });
 
-        Context ctx = InstrumentationRegistry.getContext();
-        ctx.startActivity(new Intent(ctx, ActivityA.class));
+        Context context = getInstrumentation().getContext();
+        context.startActivity(new Intent(context, ActivityA.class));
         UiDevice.getInstance(getInstrumentation()).waitForIdle();
         synchronized (sLock) {
-            Assert.assertTrue(sTaskStackChangedCalled);
+            assertTrue(sTaskStackChangedCalled);
         }
-        Assert.assertTrue(sActivityBResumed);
+        assertTrue(sActivityBResumed);
     }
 
     @Test
@@ -101,17 +100,17 @@
         final Object[] params = new Object[2];
         final CountDownLatch latch = new CountDownLatch(1);
         registerTaskStackChangedListener(new TaskStackListener() {
-            int taskId = -1;
+            int mTaskId = -1;
 
             @Override
             public void onTaskCreated(int taskId, ComponentName componentName)
                     throws RemoteException {
-                this.taskId = taskId;
+                mTaskId = taskId;
             }
             @Override
             public void onTaskDescriptionChanged(int taskId, TaskDescription td)
                     throws RemoteException {
-                if (this.taskId == taskId && !TextUtils.isEmpty(td.getLabel())) {
+                if (mTaskId == taskId && !TextUtils.isEmpty(td.getLabel())) {
                     params[0] = taskId;
                     params[1] = td;
                     latch.countDown();
@@ -204,7 +203,7 @@
         activity.finishAndRemoveTask();
         waitForCallback(taskRemovalStartedLatch);
         // onTaskRemovalStarted happens before the activity's window is removed.
-        assertFalse(activity.onDetachedFromWindowCalled);
+        assertFalse(activity.mOnDetachedFromWindowCalled);
         assertEquals(id, params[0]);
 
         // Test for onTaskRemoved.
@@ -212,19 +211,18 @@
         waitForCallback(taskRemovedLatch);
         assertEquals(id, params[0]);
         waitForCallback(onDetachedFromWindowLatch);
-        assertTrue(activity.onDetachedFromWindowCalled);
+        assertTrue(activity.mOnDetachedFromWindowCalled);
     }
 
     /**
      * Starts the provided activity and returns the started instance.
      */
     private TestActivity startTestActivity(Class<?> activityClass) throws InterruptedException {
-        final Context context = InstrumentationRegistry.getContext();
-        final ActivityMonitor monitor =
-                new ActivityMonitor(activityClass.getName(), null, false);
-        InstrumentationRegistry.getInstrumentation().addMonitor(monitor);
+        final ActivityMonitor monitor = new ActivityMonitor(activityClass.getName(), null, false);
+        getInstrumentation().addMonitor(monitor);
+        final Context context = getInstrumentation().getContext();
         context.startActivity(new Intent(context, activityClass));
-        final TestActivity activity = (TestActivity)monitor.waitForActivityWithTimeout(1000);
+        final TestActivity activity = (TestActivity) monitor.waitForActivityWithTimeout(1000);
         if (activity == null) {
             throw new RuntimeException("Timed out waiting for Activity");
         }
@@ -239,11 +237,12 @@
 
     private void waitForCallback(CountDownLatch latch) {
         try {
-        final boolean result = latch.await(2, TimeUnit.SECONDS);
+            final boolean result = latch.await(2, TimeUnit.SECONDS);
             if (!result) {
                 throw new RuntimeException("Timed out waiting for task stack change notification");
             }
-        }catch (InterruptedException e) {}
+        } catch (InterruptedException e) {
+        }
     }
 
     public static class TestActivity extends Activity {
@@ -271,6 +270,7 @@
          * If isResumed is {@code true}, sleep the thread until the activity is resumed.
          * if {@code false}, sleep the thread until the activity is paused.
          */
+        @SuppressWarnings("WaitNotInLoop")
         public void waitForResumeStateChange(boolean isResumed) throws InterruptedException {
             synchronized (this) {
                 if (mIsResumed == isResumed) {
@@ -278,7 +278,7 @@
                 }
                 wait(5000);
             }
-            assertTrue("The activity resume state change timed out", mIsResumed == isResumed);
+            assertEquals("The activity resume state change timed out", isResumed, mIsResumed);
         }
     }
 
@@ -330,17 +330,17 @@
     }
 
     public static class ActivityTaskChangeCallbacks extends TestActivity {
-        boolean onDetachedFromWindowCalled = false;
-        CountDownLatch onDetachedFromWindowCountDownLatch;
+        public boolean mOnDetachedFromWindowCalled = false;
+        private CountDownLatch mOnDetachedFromWindowCountDownLatch;
 
         @Override
         public void onDetachedFromWindow() {
-            onDetachedFromWindowCalled = true;
-            onDetachedFromWindowCountDownLatch.countDown();
+            mOnDetachedFromWindowCalled = true;
+            mOnDetachedFromWindowCountDownLatch.countDown();
         }
 
         void setDetachedFromWindowLatch(CountDownLatch countDownLatch) {
-            onDetachedFromWindowCountDownLatch = countDownLatch;
+            mOnDetachedFromWindowCountDownLatch = countDownLatch;
         }
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/wm/WindowAnimationSpecTest.java b/services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java
similarity index 96%
rename from services/tests/servicestests/src/com/android/server/wm/WindowAnimationSpecTest.java
rename to services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java
index 827d938..21e5d99 100644
--- a/services/tests/servicestests/src/com/android/server/wm/WindowAnimationSpecTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowAnimationSpecTest.java
@@ -11,7 +11,7 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
 package com.android.server.wm;
@@ -33,19 +33,17 @@
 import android.view.animation.ClipRectAnimation;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
 /**
  * Tests for the {@link WindowAnimationSpec} class.
  *
- *  atest FrameworksServicesTests:com.android.server.wm.WindowAnimationSpecTest
+ * Build/Install/Run:
+ *  atest WmTests:WindowAnimationSpecTest
  */
 @SmallTest
 @Presubmit
-@RunWith(AndroidJUnit4.class)
 public class WindowAnimationSpecTest {
     private final SurfaceControl mSurfaceControl = mock(SurfaceControl.class);
     private final SurfaceControl.Transaction mTransaction = mock(SurfaceControl.Transaction.class);
diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
new file mode 100644
index 0000000..115bcb1
--- /dev/null
+++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright (C) 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.server.wm;
+
+import static org.mockito.Mockito.any;
+import static org.mockito.Mockito.anyBoolean;
+import static org.mockito.Mockito.anyFloat;
+import static org.mockito.Mockito.anyInt;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import android.content.Context;
+import android.content.res.Configuration;
+import android.graphics.Rect;
+import android.view.Display;
+import android.view.Surface;
+
+import org.mockito.invocation.InvocationOnMock;
+
+/**
+ * A collection of static functions that can be referenced by other test packages to provide access
+ * to WindowManager related test functionality.
+ */
+public class WindowTestUtils {
+    private static int sNextTaskId = 0;
+
+    /** Retrieves an instance of a mock {@link WindowManagerService}. */
+    static WindowManagerService getMockWindowManagerService() {
+        final WindowManagerService service = mock(WindowManagerService.class);
+        final WindowManagerGlobalLock lock = new WindowManagerGlobalLock();
+        doReturn(lock).when(service).getWindowManagerLock();
+        return service;
+    }
+
+    /** An extension of {@link DisplayContent} to gain package scoped access. */
+    public static class TestDisplayContent extends DisplayContent {
+
+        private TestDisplayContent(Display display, WindowManagerService service,
+                WallpaperController wallpaperController, DisplayWindowController controller) {
+            super(display, service, wallpaperController, controller);
+        }
+
+        /** Create a mocked default {@link DisplayContent}. */
+        public static TestDisplayContent create(Context context) {
+            final TestDisplayContent displayContent = mock(TestDisplayContent.class);
+            displayContent.isDefaultDisplay = true;
+
+            final DisplayPolicy displayPolicy = mock(DisplayPolicy.class);
+            when(displayPolicy.navigationBarCanMove()).thenReturn(true);
+            when(displayPolicy.hasNavigationBar()).thenReturn(true);
+
+            final DisplayRotation displayRotation = new DisplayRotation(
+                    mock(WindowManagerService.class), displayContent, displayPolicy,
+                    context, new Object());
+            displayRotation.mPortraitRotation = Surface.ROTATION_0;
+            displayRotation.mLandscapeRotation = Surface.ROTATION_90;
+            displayRotation.mUpsideDownRotation = Surface.ROTATION_180;
+            displayRotation.mSeascapeRotation = Surface.ROTATION_270;
+
+            when(displayContent.getDisplayRotation()).thenReturn(displayRotation);
+
+            return displayContent;
+        }
+    }
+
+    /**
+     * Creates a mock instance of {@link StackWindowController}.
+     */
+    public static StackWindowController createMockStackWindowContainerController() {
+        StackWindowController controller = mock(StackWindowController.class);
+        controller.mContainer = mock(TestTaskStack.class);
+
+        // many components rely on the {@link StackWindowController#adjustConfigurationForBounds}
+        // to properly set bounds values in the configuration. We must mimick those actions here.
+        doAnswer((InvocationOnMock invocationOnMock) -> {
+            final Configuration config = invocationOnMock.<Configuration>getArgument(7);
+            final Rect bounds = invocationOnMock.<Rect>getArgument(0);
+            config.windowConfiguration.setBounds(bounds);
+            return null;
+        }).when(controller).adjustConfigurationForBounds(any(), any(), any(), any(),
+                anyBoolean(), anyBoolean(), anyFloat(), any(), any(), anyInt());
+
+        return controller;
+    }
+
+    /**
+     * An extension of {@link TestTaskStack}, which overrides package scoped methods that would not
+     * normally be mocked out.
+     */
+    public static class TestTaskStack extends TaskStack {
+        TestTaskStack(WindowManagerService service, int stackId) {
+            super(service, stackId, null);
+        }
+
+        @Override
+        void addTask(Task task, int position, boolean showForAllUsers, boolean moveParents) {
+            // Do nothing.
+        }
+    }
+}
diff --git a/services/tests/servicestests/src/com/android/server/wm/utils/CoordinateTransformsTest.java b/services/tests/wmtests/src/com/android/server/wm/utils/CoordinateTransformsTest.java
similarity index 98%
rename from services/tests/servicestests/src/com/android/server/wm/utils/CoordinateTransformsTest.java
rename to services/tests/wmtests/src/com/android/server/wm/utils/CoordinateTransformsTest.java
index f82b012..649b785 100644
--- a/services/tests/servicestests/src/com/android/server/wm/utils/CoordinateTransformsTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/utils/CoordinateTransformsTest.java
@@ -23,8 +23,6 @@
 
 import static com.android.server.wm.utils.CoordinateTransforms.transformLogicalToPhysicalCoordinates;
 import static com.android.server.wm.utils.CoordinateTransforms.transformPhysicalToLogicalCoordinates;
-
-
 import static com.android.server.wm.utils.CoordinateTransforms.transformToRotation;
 
 import static org.hamcrest.Matchers.is;
@@ -40,6 +38,10 @@
 import org.junit.Test;
 import org.junit.rules.ErrorCollector;
 
+/**
+ * Build/Install/Run:
+ *  atest WmTests:CoordinateTransformsTest
+ */
 public class CoordinateTransformsTest {
 
     private static final int W = 200;
@@ -202,4 +204,4 @@
     public interface TransformPointAssertable {
         void transformsTo(int x, int y);
     }
-}
\ No newline at end of file
+}
diff --git a/services/tests/servicestests/src/com/android/server/wm/utils/DisplayRotationUtilTest.java b/services/tests/wmtests/src/com/android/server/wm/utils/DisplayRotationUtilTest.java
similarity index 77%
rename from services/tests/servicestests/src/com/android/server/wm/utils/DisplayRotationUtilTest.java
rename to services/tests/wmtests/src/com/android/server/wm/utils/DisplayRotationUtilTest.java
index ba8869b..926153d 100644
--- a/services/tests/servicestests/src/com/android/server/wm/utils/DisplayRotationUtilTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/utils/DisplayRotationUtilTest.java
@@ -11,7 +11,7 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
 package com.android.server.wm.utils;
@@ -24,6 +24,7 @@
 import static android.view.Surface.ROTATION_180;
 import static android.view.Surface.ROTATION_270;
 import static android.view.Surface.ROTATION_90;
+
 import static com.android.server.wm.utils.DisplayRotationUtil.getBoundIndexFromRotation;
 
 import static org.hamcrest.Matchers.equalTo;
@@ -32,24 +33,20 @@
 import android.graphics.Rect;
 import android.platform.test.annotations.Presubmit;
 
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
-
+import org.junit.Test;
 
 /**
  * Tests for {@link DisplayRotationUtil}
  *
- * Run with: atest DisplayRotationUtilTest
+ * Build/Install/Run:
+ *  atest WmTests:DisplayRotationUtilTest
  */
-@RunWith(AndroidJUnit4.class)
 @SmallTest
 @Presubmit
 public class DisplayRotationUtilTest {
-    private static Rect ZERO_RECT = new Rect();
+    private static final Rect ZERO_RECT = new Rect();
 
     @Test
     public void testGetBoundIndexFromRotation_rot0() {
@@ -103,7 +100,7 @@
     @Test
     public void testGetRotatedBounds_top_rot0() {
         DisplayRotationUtil util = new DisplayRotationUtil();
-        Rect[] bounds = new Rect[] { ZERO_RECT, new Rect(50,0,150,10), ZERO_RECT, ZERO_RECT };
+        Rect[] bounds = new Rect[] {ZERO_RECT, new Rect(50, 0, 150, 10), ZERO_RECT, ZERO_RECT};
         assertThat(util.getRotatedBounds(bounds, ROTATION_0, 200, 300),
                 equalTo(bounds));
     }
@@ -111,31 +108,31 @@
     @Test
     public void testGetRotatedBounds_top_rot90() {
         DisplayRotationUtil util = new DisplayRotationUtil();
-        Rect[] bounds = new Rect[] { ZERO_RECT, new Rect(50,0,150,10), ZERO_RECT, ZERO_RECT };
+        Rect[] bounds = new Rect[] {ZERO_RECT, new Rect(50, 0, 150, 10), ZERO_RECT, ZERO_RECT};
         assertThat(util.getRotatedBounds(bounds, ROTATION_90, 200, 300),
-                equalTo(new Rect[] { new Rect(0, 50, 10, 150), ZERO_RECT, ZERO_RECT, ZERO_RECT }));
+                equalTo(new Rect[] {new Rect(0, 50, 10, 150), ZERO_RECT, ZERO_RECT, ZERO_RECT}));
     }
 
     @Test
     public void testGetRotatedBounds_top_rot180() {
         DisplayRotationUtil util = new DisplayRotationUtil();
-        Rect[] bounds = new Rect[] { ZERO_RECT, new Rect(50,0,150,10), ZERO_RECT, ZERO_RECT };
+        Rect[] bounds = new Rect[] {ZERO_RECT, new Rect(50, 0, 150, 10), ZERO_RECT, ZERO_RECT};
         assertThat(util.getRotatedBounds(bounds, ROTATION_180, 200, 300),
-                equalTo(new Rect[] { ZERO_RECT, ZERO_RECT, ZERO_RECT, new Rect(50, 290, 150, 300) }));
+                equalTo(new Rect[] {ZERO_RECT, ZERO_RECT, ZERO_RECT, new Rect(50, 290, 150, 300)}));
     }
 
     @Test
     public void testGetRotatedBounds_top_rot270() {
         DisplayRotationUtil util = new DisplayRotationUtil();
-        Rect[] bounds = new Rect[] { ZERO_RECT, new Rect(50,0,150,10), ZERO_RECT, ZERO_RECT };
+        Rect[] bounds = new Rect[] {ZERO_RECT, new Rect(50, 0, 150, 10), ZERO_RECT, ZERO_RECT};
         assertThat(util.getRotatedBounds(bounds, ROTATION_270, 200, 300),
-                equalTo(new Rect[] { ZERO_RECT, ZERO_RECT, new Rect(290, 50, 300, 150), ZERO_RECT }));
+                equalTo(new Rect[] {ZERO_RECT, ZERO_RECT, new Rect(290, 50, 300, 150), ZERO_RECT}));
     }
 
     @Test
     public void testGetRotatedBounds_left_rot0() {
         DisplayRotationUtil util = new DisplayRotationUtil();
-        Rect[] bounds = new Rect[] { new Rect(0, 50, 10, 150), ZERO_RECT, ZERO_RECT, ZERO_RECT };
+        Rect[] bounds = new Rect[] {new Rect(0, 50, 10, 150), ZERO_RECT, ZERO_RECT, ZERO_RECT};
         assertThat(util.getRotatedBounds(bounds, ROTATION_0, 300, 200),
                 equalTo(bounds));
     }
@@ -143,24 +140,24 @@
     @Test
     public void testGetRotatedBounds_left_rot90() {
         DisplayRotationUtil util = new DisplayRotationUtil();
-        Rect[] bounds = new Rect[] { new Rect(0, 50, 10, 150), ZERO_RECT, ZERO_RECT, ZERO_RECT };
+        Rect[] bounds = new Rect[] {new Rect(0, 50, 10, 150), ZERO_RECT, ZERO_RECT, ZERO_RECT};
         assertThat(util.getRotatedBounds(bounds, ROTATION_90, 300, 200),
-                equalTo(new Rect[]{ ZERO_RECT, ZERO_RECT, ZERO_RECT, new Rect(50, 290, 150, 300) }));
+                equalTo(new Rect[] {ZERO_RECT, ZERO_RECT, ZERO_RECT, new Rect(50, 290, 150, 300)}));
     }
 
     @Test
     public void testGetRotatedBounds_left_rot180() {
         DisplayRotationUtil util = new DisplayRotationUtil();
-        Rect[] bounds = new Rect[] { new Rect(0, 50, 10, 150), ZERO_RECT, ZERO_RECT, ZERO_RECT };
+        Rect[] bounds = new Rect[] {new Rect(0, 50, 10, 150), ZERO_RECT, ZERO_RECT, ZERO_RECT};
         assertThat(util.getRotatedBounds(bounds, ROTATION_180, 300, 200),
-                equalTo(new Rect[]{ ZERO_RECT, ZERO_RECT, new Rect(290, 50, 300, 150), ZERO_RECT }));
+                equalTo(new Rect[] {ZERO_RECT, ZERO_RECT, new Rect(290, 50, 300, 150), ZERO_RECT}));
     }
 
     @Test
     public void testGetRotatedBounds_left_rot270() {
         DisplayRotationUtil util = new DisplayRotationUtil();
-        Rect[] bounds = new Rect[] { new Rect(0, 50, 10, 150), ZERO_RECT, ZERO_RECT, ZERO_RECT };
+        Rect[] bounds = new Rect[] {new Rect(0, 50, 10, 150), ZERO_RECT, ZERO_RECT, ZERO_RECT};
         assertThat(util.getRotatedBounds(bounds, ROTATION_270, 300, 200),
-                equalTo(new Rect[]{ ZERO_RECT, new Rect(50, 0, 150, 10), ZERO_RECT, ZERO_RECT }));
+                equalTo(new Rect[] {ZERO_RECT, new Rect(50, 0, 150, 10), ZERO_RECT, ZERO_RECT}));
     }
 }
diff --git a/services/tests/servicestests/src/com/android/server/wm/utils/InsetUtilsTest.java b/services/tests/wmtests/src/com/android/server/wm/utils/InsetUtilsTest.java
similarity index 92%
rename from services/tests/servicestests/src/com/android/server/wm/utils/InsetUtilsTest.java
rename to services/tests/wmtests/src/com/android/server/wm/utils/InsetUtilsTest.java
index 3364aef..089e908 100644
--- a/services/tests/servicestests/src/com/android/server/wm/utils/InsetUtilsTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/utils/InsetUtilsTest.java
@@ -11,7 +11,7 @@
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License
+ * limitations under the License.
  */
 
 package com.android.server.wm.utils;
@@ -27,18 +27,19 @@
 import android.platform.test.annotations.Presubmit;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
-@RunWith(AndroidJUnit4.class)
+/**
+ * Build/Install/Run:
+ *  atest WmTests:InsetUtilsTest
+ */
 @SmallTest
 @Presubmit
 public class InsetUtilsTest {
 
     @Test
-    public void testAdd() throws Exception {
+    public void testAdd() {
         final Rect rect1 = new Rect(10, 20, 30, 40);
         final Rect rect2 = new Rect(50, 60, 70, 80);
         InsetUtils.addInsets(rect1, rect2);
diff --git a/services/tests/servicestests/src/com/android/server/wm/utils/RotationCacheTest.java b/services/tests/wmtests/src/com/android/server/wm/utils/RotationCacheTest.java
similarity index 88%
rename from services/tests/servicestests/src/com/android/server/wm/utils/RotationCacheTest.java
rename to services/tests/wmtests/src/com/android/server/wm/utils/RotationCacheTest.java
index 5d08920..33f34b4 100644
--- a/services/tests/servicestests/src/com/android/server/wm/utils/RotationCacheTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/utils/RotationCacheTest.java
@@ -28,13 +28,14 @@
 
 import androidx.test.filters.FlakyTest;
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Before;
 import org.junit.Test;
-import org.junit.runner.RunWith;
 
-@RunWith(AndroidJUnit4.class)
+/**
+ * Build/Install/Run:
+ *  atest WmTests:RotationCacheTest
+ */
 @SmallTest
 @FlakyTest(bugId = 74078662)
 @Presubmit
@@ -53,7 +54,7 @@
     }
 
     @Test
-    public void getOrCompute_computes() throws Exception {
+    public void getOrCompute_computes() {
         assertThat(mCache.getOrCompute("hello", 0), equalTo(create("hello", 0)));
         assertThat(mCache.getOrCompute("hello", 1), equalTo(create("hello", 1)));
         assertThat(mCache.getOrCompute("hello", 2), equalTo(create("hello", 2)));
@@ -61,7 +62,7 @@
     }
 
     @Test
-    public void getOrCompute_sameParam_sameRot_hitsCache() throws Exception {
+    public void getOrCompute_sameParam_sameRot_hitsCache() {
         assertNotNull(mCache.getOrCompute("hello", 1));
 
         mComputationCalled = false;
@@ -70,7 +71,7 @@
     }
 
     @Test
-    public void getOrCompute_sameParam_hitsCache_forAllRots() throws Exception {
+    public void getOrCompute_sameParam_hitsCache_forAllRots() {
         assertNotNull(mCache.getOrCompute("hello", 3));
         assertNotNull(mCache.getOrCompute("hello", 2));
         assertNotNull(mCache.getOrCompute("hello", 1));
@@ -85,14 +86,14 @@
     }
 
     @Test
-    public void getOrCompute_changingParam_recomputes() throws Exception {
+    public void getOrCompute_changingParam_recomputes() {
         assertNotNull(mCache.getOrCompute("hello", 1));
 
         assertThat(mCache.getOrCompute("world", 1), equalTo(create("world", 1)));
     }
 
     @Test
-    public void getOrCompute_changingParam_clearsCacheForDifferentRots() throws Exception {
+    public void getOrCompute_changingParam_clearsCacheForDifferentRots() {
         assertNotNull(mCache.getOrCompute("hello", 1));
         assertNotNull(mCache.getOrCompute("world", 2));
 
diff --git a/services/tests/servicestests/src/com/android/server/wm/utils/WmDisplayCutoutTest.java b/services/tests/wmtests/src/com/android/server/wm/utils/WmDisplayCutoutTest.java
similarity index 96%
rename from services/tests/servicestests/src/com/android/server/wm/utils/WmDisplayCutoutTest.java
rename to services/tests/wmtests/src/com/android/server/wm/utils/WmDisplayCutoutTest.java
index c5e35e7..fb8ba7b 100644
--- a/services/tests/servicestests/src/com/android/server/wm/utils/WmDisplayCutoutTest.java
+++ b/services/tests/wmtests/src/com/android/server/wm/utils/WmDisplayCutoutTest.java
@@ -16,12 +16,11 @@
 
 package com.android.server.wm.utils;
 
-
-import static android.view.DisplayCutout.NO_CUTOUT;
 import static android.view.DisplayCutout.BOUNDS_POSITION_BOTTOM;
 import static android.view.DisplayCutout.BOUNDS_POSITION_LEFT;
 import static android.view.DisplayCutout.BOUNDS_POSITION_RIGHT;
 import static android.view.DisplayCutout.BOUNDS_POSITION_TOP;
+import static android.view.DisplayCutout.NO_CUTOUT;
 import static android.view.DisplayCutout.fromBoundingRect;
 
 import static org.hamcrest.Matchers.equalTo;
@@ -29,7 +28,6 @@
 import static org.junit.Assert.assertNotEquals;
 import static org.junit.Assert.assertThat;
 
-
 import android.graphics.Insets;
 import android.graphics.Rect;
 import android.platform.test.annotations.Presubmit;
@@ -37,24 +35,18 @@
 import android.view.DisplayCutout;
 
 import androidx.test.filters.SmallTest;
-import androidx.test.runner.AndroidJUnit4;
 
 import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import java.util.Arrays;
 
 /**
  * Tests for {@link WmDisplayCutout}
  *
- * Run with: atest WmDisplayCutoutTest
+ * Build/Install/Run:
+ *  atest WmTests:WmDisplayCutoutTest
  */
-@RunWith(AndroidJUnit4.class)
 @SmallTest
 @Presubmit
 public class WmDisplayCutoutTest {
-    private static final Rect ZERO_RECT = new Rect();
-
     private final DisplayCutout mCutoutTop = new DisplayCutout(
             Insets.of(0, 100, 0, 0),
             null /* boundLeft */, new Rect(50, 0, 75, 100) /* boundTop */,
@@ -165,4 +157,4 @@
         assertEquals(new WmDisplayCutout(mCutoutTop, new Size(1, 2)).hashCode(),
                 new WmDisplayCutout(mCutoutTop, new Size(1, 2)).hashCode());
     }
-}
\ No newline at end of file
+}
diff --git a/telecomm/java/android/telecom/TelecomManager.java b/telecomm/java/android/telecom/TelecomManager.java
index 3127b35..fa16bfe 100644
--- a/telecomm/java/android/telecom/TelecomManager.java
+++ b/telecomm/java/android/telecom/TelecomManager.java
@@ -15,6 +15,7 @@
 package android.telecom;
 
 import android.Manifest;
+import android.annotation.NonNull;
 import android.annotation.RequiresPermission;
 import android.annotation.SuppressAutoDoc;
 import android.annotation.SuppressLint;
@@ -175,6 +176,33 @@
             "android.telecom.extra.CHANGE_DEFAULT_DIALER_PACKAGE_NAME";
 
     /**
+     * Broadcast intent action indicating that the current default call screening app has changed.
+     *
+     * The string extra {@link #EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME} will contain the
+     * name of the Component of the previous or the new call screening app.
+     *
+     * The boolean extra {@link #EXTRA_IS_DEFAULT_CALL_SCREENING_APP} will indicate the component
+     * name in the String extra {@link #EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME} is default
+     * call screening app or not.
+     */
+    public static final String ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED =
+        "android.telecom.action.DEFAULT_CALL_SCREENING_APP_CHANGED";
+
+    /**
+     * Extra value used with {@link #ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED} broadcast to
+     * indicate the ComponentName of the call screening app which has changed.
+     */
+    public static final String EXTRA_DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME =
+            "android.telecom.extra.DEFAULT_CALL_SCREENING_APP_COMPONENT_NAME";
+
+    /**
+     * Extra value used with {@link #ACTION_DEFAULT_CALL_SCREENING_APP_CHANGED} broadcast to
+     * indicate whether an app is the default call screening app.
+     */
+    public static final String EXTRA_IS_DEFAULT_CALL_SCREENING_APP =
+            "android.telecom.extra.IS_DEFAULT_CALL_SCREENING_APP";
+
+    /**
      * Optional extra for {@link android.content.Intent#ACTION_CALL} containing a boolean that
      * determines whether the speakerphone should be automatically turned on for an outgoing call.
      */
@@ -1169,6 +1197,79 @@
     }
 
     /**
+     * Used to trigger display of the ChangeDefaultCallScreeningApp activity to prompt the user to
+     * change the call screening app.
+     *
+     * A {@link SecurityException} will be thrown if calling package name doesn't match the package
+     * of the passed {@link ComponentName}
+     *
+     * @param componentName to verify that the calling package name matches the package of the
+     * passed ComponentName.
+     */
+    public void requestChangeDefaultCallScreeningApp(@NonNull ComponentName componentName) {
+        try {
+            if (isServiceConnected()) {
+                getTelecomService().requestChangeDefaultCallScreeningApp(componentName, mContext
+                    .getOpPackageName());
+            }
+        } catch (RemoteException e) {
+            Log.e(TAG,
+                "RemoteException calling ITelecomService#requestChangeDefaultCallScreeningApp.",
+                e);
+        }
+    }
+
+    /**
+     * Used to verify that the passed ComponentName is default call screening app.
+     *
+     * @param componentName to verify that the package of the passed ComponentName matched the default
+     * call screening packageName.
+     *
+     * @return {@code true} if the passed componentName matches the default call screening's, {@code
+     * false} if the passed componentName is null, or it doesn't match default call screening's.
+     */
+    public boolean isDefaultCallScreeningApp(ComponentName componentName) {
+        try {
+            if (isServiceConnected()) {
+                return getTelecomService().isDefaultCallScreeningApp(componentName);
+            }
+        } catch (RemoteException e) {
+            Log.e(TAG,
+                "RemoteException calling ITelecomService#isDefaultCallScreeningApp.",
+                e);
+        }
+        return false;
+    }
+
+    /**
+     * Used to set the default call screening package.
+     *
+     * Requires permission: {@link android.Manifest.permission#MODIFY_PHONE_STATE} Requires
+     * permission: {@link android.Manifest.permission#WRITE_SECURE_SETTINGS}
+     *
+     * A {@link IllegalArgumentException} will be thrown if the specified package and component name
+     * of {@link ComponentName} does't exist, or the specified component of {@link ComponentName}
+     * does't have {@link android.Manifest.permission#BIND_SCREENING_SERVICE}.
+     *
+     * @param componentName to set the default call screening to.
+     * @hide
+     */
+    @RequiresPermission(anyOf = {
+        android.Manifest.permission.MODIFY_PHONE_STATE,
+        android.Manifest.permission.WRITE_SECURE_SETTINGS
+    })
+    public void setDefaultCallScreeningApp(ComponentName componentName) {
+        try {
+            if (isServiceConnected()) {
+                getTelecomService().setDefaultCallScreeningApp(componentName);
+            }
+        } catch (RemoteException e) {
+            Log.e(TAG,
+                "RemoteException calling ITelecomService#setDefaultCallScreeningApp.", e);
+        }
+    }
+
+    /**
      * Return whether a given phone number is the configured voicemail number for a
      * particular phone account.
      *
diff --git a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
index df7d683..d97f0c5 100644
--- a/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
+++ b/telecomm/java/com/android/internal/telecom/ITelecomService.aidl
@@ -256,6 +256,21 @@
     boolean setDefaultDialer(in String packageName);
 
     /**
+     * @see TelecomServiceImpl#requestChangeDefaultCallScreeningApp
+     */
+    void requestChangeDefaultCallScreeningApp(in ComponentName componentNamem, String callingPackage);
+
+    /**
+     * @see TelecomServiceImpl#isDefaultCallScreeningApp
+     */
+    boolean isDefaultCallScreeningApp(in ComponentName componentName);
+
+    /**
+     * @see TelecomServiceImpl#setDefaultCallScreeningApp
+     */
+    void setDefaultCallScreeningApp(in ComponentName componentName);
+
+    /**
     * @see TelecomServiceImpl#createManageBlockedNumbersIntent
     **/
     Intent createManageBlockedNumbersIntent();
diff --git a/telephony/java/android/provider/Telephony.java b/telephony/java/android/provider/Telephony.java
index 52ac32d..d7024cf 100644
--- a/telephony/java/android/provider/Telephony.java
+++ b/telephony/java/android/provider/Telephony.java
@@ -16,6 +16,7 @@
 
 package android.provider;
 
+import android.annotation.RequiresPermission;
 import android.annotation.SdkConstant;
 import android.annotation.SdkConstant.SdkConstantType;
 import android.annotation.SystemApi;
@@ -1271,6 +1272,31 @@
              */
             public static final String EXTRA_IS_INITIAL_CREATE =
                     "android.provider.extra.IS_INITIAL_CREATE";
+
+            /**
+             * Broadcast intent action indicating that the telephony provider SMS MMS database is
+             * corrupted. A boolean is specified in {@link #EXTRA_IS_CORRUPTED} to indicate if the
+             * database is corrupted. Requires the
+             * {@link android.Manifest.permission#READ_PRIVILEGED_PHONE_STATE permission.
+             *
+             * @hide
+             */
+            @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
+            @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE)
+            public static final String ACTION_SMS_MMS_DB_LOST =
+                    "android.provider.action.SMS_MMS_DB_LOST";
+
+            /**
+             * Boolean flag passed as an extra with {@link #ACTION_SMS_MMS_DB_LOST} to indicate
+             * whether the DB got corrupted or not.
+             *
+             * @see #ACTION_SMS_MMS_DB_LOST
+             *
+             * @hide
+             */
+            public static final String EXTRA_IS_CORRUPTED =
+                    "android.provider.extra.IS_CORRUPTED";
+
             /**
              * Read the PDUs out of an {@link #SMS_RECEIVED_ACTION} or a
              * {@link #DATA_SMS_RECEIVED_ACTION} intent.
diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java
index e5c4ccd..8a77f14 100644
--- a/telephony/java/android/telephony/TelephonyManager.java
+++ b/telephony/java/android/telephony/TelephonyManager.java
@@ -1238,38 +1238,6 @@
      */
     public static final String EXTRA_RECOVERY_ACTION = "recoveryAction";
 
-     /**
-     * Broadcast intent action indicating that the telephony provider DB got lost.
-     *
-     * <p>
-     * The {@link #EXTRA_IS_CORRUPTED} extra indicates whether the database is lost
-     * due to corruption or not
-     *
-     * <p class="note">
-     * Requires the MODIFY_PHONE_STATE permission.
-     *
-     * <p class="note">
-     * This is a protected intent that can only be sent by the system.
-     *
-     * @see #EXTRA_IS_CORRUPTED
-     *
-     * @hide
-     */
-    @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION)
-    @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE)
-    public static final String ACTION_MMSSMS_DATABASE_LOST =
-            "android.intent.action.MMSSMS_DATABASE_LOST";
-
-    /**
-     * A boolean extra used with {@link #ACTION_MMSSMS_DATABASE_LOST} to indicate
-     * whether the database is lost due to corruption or not.
-     *
-     * @see #ACTION_MMSSMS_DATABASE_LOST
-     *
-     * @hide
-     */
-    public static final String EXTRA_IS_CORRUPTED = "isCorrupted";
-
     //
     //
     // Device Info
diff --git a/telephony/java/android/telephony/data/IQualifiedNetworksServiceCallback.aidl b/telephony/java/android/telephony/data/IQualifiedNetworksServiceCallback.aidl
index e8e1f01..32ffdbc 100644
--- a/telephony/java/android/telephony/data/IQualifiedNetworksServiceCallback.aidl
+++ b/telephony/java/android/telephony/data/IQualifiedNetworksServiceCallback.aidl
@@ -22,5 +22,5 @@
  */
 oneway interface IQualifiedNetworksServiceCallback
 {
-    void onQualifiedNetworkTypesChanged(int apnType, in int[] qualifiedNetworkTypesList);
+    void onQualifiedNetworkTypesChanged(int apnTypes, in int[] qualifiedNetworkTypes);
 }
diff --git a/telephony/java/android/telephony/data/QualifiedNetworksService.java b/telephony/java/android/telephony/data/QualifiedNetworksService.java
index bb89f19..57d9cce 100644
--- a/telephony/java/android/telephony/data/QualifiedNetworksService.java
+++ b/telephony/java/android/telephony/data/QualifiedNetworksService.java
@@ -121,27 +121,28 @@
         /**
          * Update the qualified networks list. Network availability updater must invoke this method
          * whenever the qualified networks changes. If this method is never invoked for certain
-         * APN type, then frameworks will always use the default (i.e. cellular) data and network
+         * APN types, then frameworks will always use the default (i.e. cellular) data and network
          * service.
          *
-         * @param apnType APN type of the qualified networks
+         * @param apnTypes APN types of the qualified networks. This must be a bitmask combination
+         * of {@link ApnSetting.ApnType}.
          * @param qualifiedNetworkTypes List of network types which are qualified for data
          * connection setup for {@link @apnType} in the preferred order. Each element in the array
          * is a {@link AccessNetworkType}. An empty list or null indicates no networks are qualified
          * for data setup.
          */
-        public final void updateQualifiedNetworkTypes(@ApnType int apnType,
+        public final void updateQualifiedNetworkTypes(@ApnType int apnTypes,
                                                       int[] qualifiedNetworkTypes) {
-            mHandler.obtainMessage(QNS_UPDATE_QUALIFIED_NETWORKS, mSlotIndex, apnType,
+            mHandler.obtainMessage(QNS_UPDATE_QUALIFIED_NETWORKS, mSlotIndex, apnTypes,
                     qualifiedNetworkTypes).sendToTarget();
         }
 
-        private void onUpdateQualifiedNetworkTypes(@ApnType int apnType,
+        private void onUpdateQualifiedNetworkTypes(@ApnType int apnTypes,
                                                    int[] qualifiedNetworkTypes) {
-            mQualifiedNetworkTypesList.put(apnType, qualifiedNetworkTypes);
+            mQualifiedNetworkTypesList.put(apnTypes, qualifiedNetworkTypes);
             if (mCallback != null) {
                 try {
-                    mCallback.onQualifiedNetworkTypesChanged(apnType, qualifiedNetworkTypes);
+                    mCallback.onQualifiedNetworkTypesChanged(apnTypes, qualifiedNetworkTypes);
                 } catch (RemoteException e) {
                     loge("Failed to call onQualifiedNetworksChanged. " + e);
                 }